题目:设计修改程序,以确保 two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行。
|
方法1: 用两个boolean变量flag1和flag2控制,当第一个线程结束,flag1=true; 线程2只有当flag1=true时,才能执行; 线程3只有当flag2=true时,才能执行。 |
class Foo {
public Foo() {
}
Thread t1,t2;
boolean flag1 = false;
boolean flag2 = false;
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
// t1 = Thread.currentThread();
printFirst.run();
flag1 = true;
}
public void second(Runnable printSecond) throws InterruptedException {
// printSecond.run() outputs "second". Do not change or remove this line.
while(!flag1){}
printSecond.run();
flag2 = true;
}
public void third(Runnable printThird) throws InterruptedException {
// printThird.run() outputs "third". Do not change or remove this line.
while(!flag2){}
// t2.join();
printThird.run();
}
}
|
![]() |
|
方法2:join 获取执行first的线程t1和执行second的线程t2,t1和t2初始值为null; 当获取到t1时,t2会等到t1执行完才继续执行; 同样,t3会等到t2执行完之后,才会执行。 |
class Foo {
Thread t1,t2;
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
t1 = Thread.currentThread();
printFirst.run();
}
public void second(Runnable printSecond) throws InterruptedException {
while(t1 == null){};
t1.join();
t2 = Thread.currentThread();
printSecond.run();
}
public void third(Runnable printThird) throws InterruptedException {
while(t2 == null){};
t2.join();
printThird.run();
}
}
|
![]() |
|
方法3:wait/notifyAll 使用变整型量mark控制线程2和线程3的执行顺序, wait/notifyAll方法需要配合synchronized代码块使用,线程1执行之后,会释放锁。 |
class Foo {
private int mark = 0;
private Object lock = new Object();
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
synchronized(lock){
printFirst.run();
mark = 1;
lock.notifyAll();
}
}
public void second(Runnable printSecond) throws InterruptedException {
synchronized(lock){
while (mark != 1){ lock.wait(); }
printSecond.run();
mark = 2;
lock.notifyAll();
}
}
public void third(Runnable printThird) throws InterruptedException {
synchronized(lock){
while (mark != 2){ lock.wait(); }
printThird.run();
// lock.notifyAll();
}
}
}
|
![]() |
|
方法4:CountDownLatch 用两个CountDownLatch实现,当第一个线程执行完毕,latch1减1为0,线程2就会被激活,当线程2执行完成,latch2减1为0,线程3就会被激活。 |
import java.util.concurrent.CountDownLatch;
class Foo {
CountDownLatch latch1 = new CountDownLatch(1);
CountDownLatch latch2 = new CountDownLatch(1);
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
latch1.countDown();
}
public void second(Runnable printSecond) throws InterruptedException {
latch1.await();
printSecond.run();
latch2.countDown();
}
public void third(Runnable printThird) throws InterruptedException {
latch2.await();
printThird.run();
}
}
|
![]() |
原文:https://www.cnblogs.com/nxf-rabbit75/p/13080305.html