-1
我一直希望解决Java中的关键部分问题。第一个进程进入无限while循环,这应该以状态之间的控制变化结束,这导致转向变量被重置。但第二个线程似乎并没有完成它的工作。任何人都可以告诉我为什么以及如何解决它?Java中使用线程的关键部分
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
class ty{
class Control{
public volatile AtomicBoolean turn=new AtomicBoolean();
}
final Control control=new Control();
}
class newthread implements Runnable{
Thread g;
ty t=new ty();
newthread(){
g=new Thread(this,"hello");
g.start();
}
@Override
public synchronized void run(){
while ((t.control.turn).get()==false){
try {
g.sleep(2000);
}
catch (InterruptedException ex) {
Logger.getLogger(newthread.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("process "+t.control.turn+"is executing");
}
System.out.println("process "+ t.control.turn+ " is executing");
(t.control.turn).compareAndSet(false, true);
}
}
class newthreadt implements Runnable{
Thread g;
ty t=new ty();
newthreadt(){
g=new Thread(this,"hello1");
g.start();
}
@Override
public synchronized void run(){
while ((t.control.turn).get()==true){
try {
g.sleep(1000);
} catch (InterruptedException ex){
Logger.getLogger(newthreadt.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("process "+t.control.turn+"is executing");
}
System.out.println("process "+t.control.turn+"is executing");
(t.control.turn).compareAndSet(true, false);
}
}
public class JavaApplication2 {
public static void main(String[] args){
int turn=0;
newthread f;
newthreadt g;
new newthread();
new newthreadt();
}
}
请修复缩进,以当前形式阅读代码非常困难 –
您可以删除尽可能多的代码。 esp的代码,它不会做任何事情。我还建议你使用Java Code Conventions,比如'TitleCase'类名。 –
我强烈建议避免在构造函数中创建线程或在实例变量上调用像Thread.sleep这样的静态方法。 –