我想创建两个Threads
。一个用于显示内容,之后它将转到等待状态。然后第二个线程应该开始执行,它应该打印状态第一个线程(即等待状态),显示后应该通知,第一个线程应该继续执行。
答案 0 :(得分:0)
我为你创建了一个小程序。请检查它是否符合您的要求。我们可以稍后美化代码。如果不符合您的期望,请详细说明您的要求。
public class Main {
public static void main(String[] args) {
MyThread1 th1 = new MyThread1();
MyThread2 th2 = new MyThread2();
//Allow thread 1 to run first
Shareable shareable = new Shareable();
shareable.threadToRun = th1.getName();
th1.setAnotherThread(th2);
th1.setShareable(shareable);
th2.setAnotherThread(th1);
th2.setShareable(shareable);
th1.start();
th2.start();
}
}
class Shareable {
volatile String threadToRun;
}
class MyThread1 extends Thread {
private Shareable shareable;
private Thread anotherThread;
@Override
public void run() {
synchronized (shareable) {
waitForTurn();
System.out.println(getName() + " I am doing first task. After that wait for next Thread to finish.");
shareable.threadToRun = anotherThread.getName();
shareable.notifyAll();
waitForTurn();
System.out.println(getName() + " I am doing next task now.");
}
}
private void waitForTurn(){
if(!shareable.threadToRun.equals(getName())){
try {
shareable.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void setShareable(Shareable shareable){
this.shareable = shareable;
}
public void setAnotherThread(Thread anotherThread){
this.anotherThread = anotherThread;
}
}
class MyThread2 extends Thread {
private Shareable shareable;
private Thread anotherThread;
@Override
public void run() {
synchronized (shareable) {
waitForTurn();
System.out.println(getName() + " I am doing task now. Another Thread " + anotherThread.getName() + " is in state " + anotherThread.getState());
shareable.threadToRun = anotherThread.getName();
shareable.notifyAll();
}
}
private void waitForTurn(){
if(!shareable.threadToRun.equals(getName())){
try {
shareable.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void setShareable(Shareable shareable){
this.shareable = shareable;
}
public void setAnotherThread(Thread anotherThread){
this.anotherThread = anotherThread;
}
}
这是输出:
Thread-0 I am doing first task. After that wait for next Thread to finish.
Thread-1 I am doing task now. Another Thread Thread-0 is in state WAITING
Thread-0 I am doing next task now.