三个不同的线程 A、B、C 将会共用一个 Foo 实例。
一个将会调用 first() 方法
一个将会调用 second() 方法
还有一个将会调用 third() 方法
请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。
题目来源:https://leetcode-cn.com/problems/print-in-order
/**
*@Title Foo.java
*@description TODO
*@time 2021年3月16日 下午12:29:10
*@author lyj
*@version 1.0
**/
package org.threadTest;
import java.util.concurrent.CountDownLatch;
/**
* @author lyj
*
*/
public class Foo {
/**
* @Title: main
* @Description:
* @param args
* @return void
* @author lyj
* @date 2021年3月16日下午12:29:10
*/
private CountDownLatch countDownLatchA;
private CountDownLatch countDownLatchB;
public Foo() {
countDownLatchA = new CountDownLatch(1);
countDownLatchB = new CountDownLatch(1);
}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
countDownLatchA.countDown();
}
public void second(Runnable printSecond) throws InterruptedException {
// printSecond.run() outputs "second". Do not change or remove this line.
countDownLatchA.await();
printSecond.run();
countDownLatchB.countDown();
}
public void third(Runnable printThird) throws InterruptedException {
// printThird.run() outputs "third". Do not change or remove this line.
countDownLatchB.await();
printThird.run();
}
}
/**
*@Title OrderPrintThread.java
*@description TODO
*@time 2021年3月16日 下午12:23:28
*@author liuyijiao
*@version 1.0
**/
package org.threadTest;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author lyj
*
*/
public class OrderPrintThread {
/**
* @Title: main
* @Description:
* @param args
* @return void
* @author lyj
* @date 2021年3月16日下午12:23:29
*/
public Thread printFirst() {
Thread thread=new Thread(
new Runnable() {
public void run() {
System.out.print("first");
}
});
return thread;
}
public Thread printSecond() {
Thread thread=new Thread(
new Runnable() {
public void run() {
System.out.print("sencond");
}
});
return thread;
}
public Thread printThird() {
Thread thread=new Thread(
new Runnable() {
public void run() {
System.out.print("third");
}
});
return thread;
}
public void toStartThread(int threadName,Foo foo) throws InterruptedException {
if(threadName==1) {
foo.first(printFirst());
}else if(threadName==2) {
foo.second(printSecond());
}else if(threadName==3) {
foo.third(printThird());
}
}
public static void main(String[] args) {
//args=1 2 3 //3 2 1 // 2 1 3
ExecutorService es=Executors.newFixedThreadPool(3);
Foo foo=new Foo();
OrderPrintThread opt=new OrderPrintThread();
for(int i=0;i<3;i++) {
int local=i;
es.execute(new Runnable() {
@Override
public void run() {
try {
int arg=Integer.valueOf(args[local]);
opt.toStartThread(arg, foo);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
es.shutdown();
}
}