如果你有三个线程,分别为T1,T2,T3,如何让线程T2在线程T1之后执行,在线程T3之前执行
import java.util.concurrent.atomic.AtomicInteger;
/**
* Hello world!
*
*/
public class App {
private static AtomicInteger i =
new AtomicInteger(
1);
public static void main(String[] args) {
Thread t1 =
new Thread(
new Runnable() {
@Override
public void run() {
synchronized (i) {
while(i.get()!=
1) {
try {
i.notifyAll();
i.wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(
1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
i.incrementAndGet();
System.out.println(
"T1====:i="+i );
i.notify();
}
}
},
"THREAD 1");
Thread t2 =
new Thread(
new Runnable() {
@Override
public void run() {
synchronized (i) {
while(i.get()!=
2) {
try {
i.notifyAll();
i.wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(
1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
i.incrementAndGet();
System.out.println(
"T2====:i="+i);
i.notify();
}
}
},
"THREAD 2");
Thread t3 =
new Thread(
new Runnable() {
@Override
public void run() {
synchronized (i) {
while(i.get()!=
3) {
try {
i.notifyAll();
i.wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(
1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
i.incrementAndGet();
System.out.println(
"T3====:i="+i);
i.notify();
}
}
},
"THREAD 3");
t3.start();
t1.start();
t2.start();
}
}
转载请注明原文地址: https://ju.6miu.com/read-1305612.html