java - 无法执行同步线程
问题描述
我尝试了教科书中关于同步线程的代码。尝试按原样编写代码。但得到错误:
cannot find symbol f.start(); and t.display();
教科书代码应该在没有同步关键字的情况下尝试。但似乎编译器无法识别该对象。请帮忙..
class First
{
synchronized void display (String s)
{
System.out.println(s);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("***");
}
}
class Second implements Runnable
{
String s;
First f;
Thread t;
public Second(First f1,String s1)
{
f=f1;
s=s1;
t=new Thread(this);
f.start();
}
public void run()
{
t.display(s);
}
}
class SyncThread
{
public static void main(String args[])
{
First f=new First();
Second ob1=new Second(f,"First");
Second ob2=new Second(f,"Second");
Second ob3=new Second(f,"Third");
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
解决方案
而不是做
t = new Thread(this);
f.start();
尝试:
t = new Thread(this);
t.start();
并在run
方法中,尝试f.display()
代替t.display()
看起来你搞砸了一些变量。尝试使用一些有意义的名称而不是f
and t
。thread.start()
搞砸andfirst.display()
比t.start()
and更难f.display()
。
推荐阅读
- python - PyGame,让坦克炮跟随你的光标,也是很好的碰撞实现实践
- javascript - 在第一次选择时将 React-select 值设置为 null
- javascript - 如何在 html 文本框中显示 javascript 输出
- alteryx - Alteryx 工作流,用于根据某些列条件从不同行中删除列值
- html - HTML
- python - 几个具有重复键但值不同且列中没有限制的字典
- java - 如何在 Jakarta-EE 项目中使用 @Resource 注入 Tomcat 数据源?
- android-widget - 在手机上将 Wear OS 表盘作为小部件运行
- javascript - 如何在图表顶部显示标签(chart.js)
- c++ - 构建 TensorFlow r1.14 C++ 文件时缺少文件“tensorflow/core/framework/types.pb.h”