这几天在学习,线程,然后通过wait()和notify()方法控制2个线程逐个依次执行.
然后就想象到,能否控制3个或者多个线程按照想要的顺序依次去执行,发型利用多把锁可以实现,但似乎并没什么实用性!
以下代码是使用同步代码块实现.
当使用同步方法实现的时候,则需要注意while与if的适应区别(不能使用if),同时注意旗帜变量的更改.
import java.util.concurrent.CountDownLatch;
public class NW {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int i=1;i<10;i++){
synchronized ("A") {
synchronized ("B") {
System.out.println("A");
"B".notify();
}
try {
"A".wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for(int i=1;i<10;i++){
synchronized ("B") {
synchronized ("C") {
System.out.println("B");
"C".notify();
}
try {
"B".wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
for(int i=1;i<10;i++){
synchronized ("C") {
synchronized ("A") {
System.out.println("C");
"A".notify();
}
try {
"C".wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
t1.start();
Thread.sleep(100);
t2.start();
Thread.sleep(100);
t3.start();
}
}