我想要实现的是,创建 2 个线程共享一个公共(public)静态 boolean 资源,以便根据标志值第一个线程应该退出,但第一个线程仍然运行。
这是下面的代码,
class SharedResource08{
public synchronized void doIt() throws Exception{
while(!SharedResource07.getBFlag()){
System.out.println(" THE THREAD "+Thread.currentThread().getName());
Thread.sleep(250);
}
}
}
class SharedResource07{
private static boolean bFLag = false;
public static synchronized void setBFlag(boolean bFLag){
bFLag = bFLag;
System.out.println(" THREAD "+Thread.currentThread().getName()+" setting value bFLag := "+bFLag);
}
public static boolean getBFlag(){
return bFLag;
}
}
class MyThread07 extends Thread{
private SharedResource08 resource;
MyThread07(String threadName,SharedResource08 resource){
super(threadName);
this.resource = resource;
}
public void run(){
try{
if(getName().equals("JACK")){
resource.doIt();
}else if(getName().equals("JILL")){
SharedResource07.setBFlag(true);
}
}catch(Exception e){
System.out.println(e);
}
}
}
public class Ex07{
public static void main(String[] args){
SharedResource08 resource = new SharedResource08();
MyThread07 t1 = new MyThread07("JACK",resource);
MyThread07 t2 = new MyThread07("JILL",resource);
t1.start();
t2.start();
}
}
我期望的是,线程 t1 将执行类 SharedResource08 的 doit() 方法, 与此同时,第二个线程 t2 应该将类 SharedResource07 的标志 bFLag 设置为真,现在一旦这个标志为真,线程 t1 应该退出方法 doIt(),
但这并没有发生,我的线程 t1 继续打印 SOP。
需要一些建议。
最佳答案
只是一个典型的错误:
改变这个:
public static synchronized void setBFlag(boolean bFLag){
bFLag = bFLag; // assigning the parameter to the parameter
为此:
public static synchronized void setBFlag(boolean bFLag){
SharedResource07.bFLag = bFLag; // assigning the parameter to the static field
一些 IDE 擅长通过在代码上发出警告信号来避免此类错误。始终随身携带 Eclipse :)
关于java - 两个线程共享静态 boolean 字段,但第一个线程仍然不退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9209976/