有一个按序打印的需求:
我们提供了一个类:
class Foo {
public void first() { System.out.println("first"); }
public void second() { System.out.println("second"); }
public void third() { System.out.println("third"); }
}
三个不同的线程将会共用一个 Foo 实例。
线程 A 将会调用 first() 方法
线程 B 将会调用 second() 方法
线程 C 将会调用 third() 方法
调用代码如下:
public static void main(String[] args) {
Foo foo = new Foo();
Thread thread1 = new Thread(() -> foo.first());
Thread thread2 = new Thread(()-> foo.second());
Thread thread3 = new Thread(()-> foo.third());
thread3.start();
thread1.start();
thread2.start();
}
某次的执行结果为(顺序不能保证):
third
second
first
请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。确保执行结果为
one
two
three
分析:
三个线程并发执行时,不能确定执行的顺序,可以定义两个AtomicInteger 类型的变量firstJobDone和secondJobDone ,在first()方法执行之后修改firstJobDone的值,只有在firstJobDone值改变以后,才能执行second()方法,second()方法执行之后修改secondJobDone的值,只有secondJobDone 的值改变后,才能执行third()方法。
Java代码如下:
Foo实现类
class Foo {
private AtomicInteger firstJobDone = new AtomicInteger(0);
private AtomicInteger secondJobDone = new AtomicInteger(0);
public Foo() {}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
firstJobDone.incrementAndGet();
}
public void second(Runnable printSecond) throws InterruptedException {
while (firstJobDone.get() != 1) {
}
printSecond.run();
secondJobDone.incrementAndGet();
}
public void third(Runnable printThird) throws InterruptedException {
while (secondJobDone.get() != 1) {
}
printThird.run();
}
}
main方法如下:
public static void main(String[] args) {
Foo foo = new Foo();
Thread thread1 = new Thread(()->{
try {
foo.first(()->System.out.println("one"));
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread2 = new Thread(()->{
try {
foo.second(()->System.out.println("two"));
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread3 = new Thread(() -> {
try {
foo.third(() -> System.out.println("three"));
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread3.start();
thread1.start();
thread2.start();
}