虽然在通常情况下每个子线程仅需要完成自己的任务即可,但是有时候我们会需要不同的线程一起协作解决某个问题,此时便需要进行线程之间的通信了。
以下的这些方法或者类将会在接下来的内容中提及:
hread.join(), object.wait(), object.notify(), CountdownLatch, CyclicBarrier, FutureTask, Callable, etc.
我将会用一些例子来讲解如何在java中实现线程间的通信。
如何使得两个线程按顺序执行
假设有两个线程:线程A与线程B。两个线程都可以按顺序打印1-3。
private static void demo1() {
Thread A = new Thread(new Runnable() {
@Override
public void run() {
printNumber("A");
}
});
Thread B = new Thread(new Runnable() {
@Override
public void run() {
printNumber("B");
}
});
A.start();
B.start();
}
相同的printNumber方法:
private static void printNumber(String threadName) {
int i=0;
while (i++ < 3) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadName + "print:" + i);
}
}
运行结果如下:
B print: 1
A print: 1
B print: 2
A print: 2
B print: 3
A print: 3
我们可以看见线程A与线程B相同时间里面打出了相同的数字。
现在,假如我们想让线程B在线程A打印完成后再进行打印,我们该如何做?
我们可以使用thread.join()
方法:
private static void demo2() {
Thread A = new Thread(new Runnable() {
@Override
public void run() {
printNumber("A");
}
});
Thread B = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("B starts waiting for A");
try {
A.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
printNumber("B");
}
});
B.start();
A.start();
}
结果如下:
B starts waiting for A
A print: 1
A print: 2
A print: 3
B print: 1
B print: 2
B print: 3
小结:我们可以使用A.join()
来使得线程B在线程A完成以后再执行。
如何使两个线程按指定的方式有序执行?
现在我们想让线程B在线程A答打印1后连续打印出1,2,3然后线程A再继续打印2,3?显然,我们需要更多的细粒度锁来控制执行顺序。
接下来,我们将介绍一下object.wait()
与object.notify()
这两个方法。
* A 1, B 1, B 2, B 3, A 2, A 3
*/
private static void demo3() {
Object lock = new Object();
Thread A = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
System.out.println("A 1");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("A 2");
System.out.println("A 3");
}
}
});
Thread B = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
System.out.println("B 1");
System.out.println("B 2");
System.out.println("B 3");
lock.notify();
}
}
});
A.start();
B.start();
}
结果如下:
A 1
A waiting…
B 1
B 2
B 3
A 2
A 3
接下来让我们思考一下发生了什么?
- 首先我们创建了对象
lock
,这个对象被线程A与线程B共用:lock = new Object()
. - 当线程A得到
lock
的时候,它首先打印了1,然后调用了lock.wait()
方法,此方法使得线程A进入等待状态并交出了lock
的控制权。 - 线程B直到线程A调用了
lock.wait()
释放控制权并且其得到lock
以后才会进行执行。 - 在得到
lock
的控制权以后,线程B开始执行并打印1,2,3,接着调用lock.notify()
方法唤醒正在等待的线程A - 线程A继续执行
接下来的代码便于理解:
private static void demo3() {
Object lock = new Object();
Thread A = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("INFO: A is waiting for the lock");
synchronized (lock) {
System.out.println("INFO: A got the lock");
System.out.println("A 1");
try {
System.out.println("INFO: A is ready to enter the wait state, giving up control of the lock");
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("INFO: B wakes up A, and A regains the lock");
System.out.println("A 2");
System.out.println("A 3");
}
}
});
Thread B = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("INFO: B is waiting for the lock");
synchronized (lock) {
System.out.println("INFO: B got the lock");
System.out.println("B 1");
System.out.println("B 2");
System.out.println("B 3");
System.out.println("INFO: B ends printing, and calling the notify method");
lock.notify();
}
}
});
A.start();
B.start();
结果:
INFO: A is waiting for the lock
INFO: A got the lock
A 1
INFO: A is ready to enter the wait state, giving up control of the lock
INFO: B is waiting for the lock
INFO: B got the lock
B 1
B 2
B 3
INFO: B ends printing, and calling the notify method
INFO: B wakes up A, and A regains the lock
A 2
A 3
小结:
1.object.wait()
与object.notify()
两者必须在同步块或者同步方法中进行(synchronized块或者synchronized方法)
2.调用某个对象的wait()
方法,相当于让当前线程交出此对象的monitor,然后进入等待状态,等待后续再次获得此对象的锁(Thread类中的sleep方法使当前线程暂停执行一段时间,从而让其他线程有机会继续执行,但它并不释放对象锁);
3.notify()
方法能够唤醒一个正在等待该对象的monitor的线程,当有多个线程都在等待该对象的monitor的话,则只能唤醒其中一个线程,具体唤醒哪个线程则不得而知。
让线程D在线程A,B,C执行完成以后同步执行
thread.join()
方法可以是一个线程在等待其他线程结束后在执行。如果我们在线程D里面依次加入A.join()
,B.join()
,C.join()
,此时他们会顺序执行(A->B->C)而不是我们所希望的同步执行。
我们要达到的目标是:A、B、C三个线程可以同时运行,各自独立完成运行后通知D;A、B、C三个线程都完成运行后,D才会开始运行。所以我们使用CountdownLatch
类来实现。其基础实现如下:
- 初始化一个
counter
:CountdownLatch countDownLatch = new CountDownLatch(3;
- 在等待线程中调用countdownloach.wait()方法,进入等待状态,直到count值变为0;
- 在其他线程中调用countdownloach.countdown()方法,该方法将使count值减少一个;
- 当其他线程中的countdown()方法将count值变为0时,等待线程中的countdownloatch.wait()方法将立即退出并继续执行以下代码。
代码如下:
private static void runDAfterABC() {
int worker = 3;
CountDownLatch countDownLatch = new CountDownLatch(worker);
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("D is waiting for other three threads");
try {
countDownLatch.await();
System.out.println("All done, D starts working");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
for (char threadName='A'; threadName <= 'C'; threadName++) {
final String tN = String.valueOf(threadName);
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(tN + "is working");
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(tN + "finished");
countDownLatch.countDown();
}
}).start();
}
}
结果如下:
D is waiting for other three threads
A is working
B is working
C is working
A finished
C finished
B finished
All done, D starts working
事实上,countdownloatch本身就是一个倒计时计数器,我们将初始计数值设置为3。当D运行时,首先调用countdownmatch.wait()方法检查计数器值是否为0,如果不是0,则保持等待状态。A、B和C分别运行完后,将使用countdownloach.countdown()方法将倒计时计数器递减1。当所有的三个都运行完后,计数器将减少到0;然后,将触发D的wait()方法以结束A、B和C,D将开始执行。
因此,countdownloatch适合于一个线程需要等待多个线程的情况。
如何让三个线程同步执行
三个线程者分开准备,然后在每个线程准备好后,他们开始同时执行。
这一次,三个线程A、B和C中的每一个都需要分别准备,然后在三个线程都准备好之后,它们开始同时运行。我们应该如何做到?
上面的countdownloatch
可以用来倒计时,但是当计数完成时,只有一个线程的await()
方法会得到响应,因此不能同时触发多个线程。
为了达到线程相互等待的效果,我们可以使用cyclicBarrier
类,其基本用途是:
- 首先创建一个公共对象cyclicbarrier,并设置同时等待的线程数,cyclicbarrier cyclicbarrier=new cyclicbarrier(3);
- 这些线程同时开始准备。准备好后,需要等待其他人完成准备,所以调用cyclicBarrier.wait()方法等待其他人;
- 当需要同时等待的指定线程都调用cyclicBarrier.await()方法时,这意味着这些线程已经准备好了,那么这些线程将开始同时继续执行。
代码:
private static void runABCWhenAllReady() {
int runner = 3;
CyclicBarrier cyclicBarrier = new CyclicBarrier(runner);
final Random random = new Random();
for (char runnerName='A'; runnerName <= 'C'; runnerName++) {
final String rN = String.valueOf(runnerName);
new Thread(new Runnable() {
@Override
public void run() {
long prepareTime = random.nextInt(10000) + 100;
System.out.println(rN + "is preparing for time:" + prepareTime);
try {
Thread.sleep(prepareTime);
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println(rN + "is prepared, waiting for others");
cyclicBarrier.await(); // The current runner is ready, waiting for others to be ready
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println(rN + "starts running"); // All the runners are ready to start running together
}
}).start();
}
}
小结:其实CyclicBarrier与CountDownLatch类似,都是计数器,只是场景不一样而已。
子线程将结果返回到主线程
在实际的开发中,我们通常需要创建子线程来完成一些耗时的任务,然后将执行结果传递回主线程。那么如何在Java中实现这一点呢?
因此,一般来说,在创建线程时,我们会将可运行对象传递给线程以供执行。runnable
的定义如下:
public interface Runnable {
public abstract void run();
}
您可以看到run()
方法在执行后不返回任何结果。那么如果你想返回结果呢?在这里,您可以使用另一个类似的可调用接口类Callable
:
@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
可以看出,Callable
的最大区别在于它返回泛型。
所以下一个问题是,如何将子线程的结果传递回来?Java有一个类FutureTask
,它可以与Callable
一起工作,但是注意获得结果的get方法会阻塞主线程。
例如,我们希望子线程计算1到100之间的和,并将结果返回到主线程。
private static void doTaskWithResultInWorker() {
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("Task starts");
Thread.sleep(1000);
int result = 0;
for (int i=0; i<=100; i++) {
result += i;
}
System.out.println("Task finished and return result");
return result;
}
};
FutureTask<Integer> futureTask = new FutureTask<>(callable);
new Thread(futureTask).start();
try {
System.out.println("Before futureTask.get()");
System.out.println("Result:" + futureTask.get());
System.out.println("After futureTask.get()");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
结果:
Before futureTask.get()
Task starts
Task finished and return result
Result: 5050
After futureTask.get()
可以看出,当主线程调用futuretask.get()
方法时,它会阻塞主线程;然后可调用文件开始在内部执行并返回操作结果;然后futuretask.get()
得到结果,主线程继续运行。
在这里我们可以了解到FutureTask
和Callable
可以直接在主线程中得到子线程的结果,但是它们会阻塞主线程。当然,如果不想阻塞主线程,可以考虑使用ExecutorService
将FutureTask
放入线程池来管理执行。
小结
多线程是现代语言的一个常见特性,线程间通信、线程同步和线程安全是非常重要的主题。