起因是在做分布式锁的时候,我在单元测试里面创建了10个线程,然后启动。每个线程都会在run方法打印内容,但是测试结果居然什么都没输出。就很纳闷,然后推测可能是主线程执行完了子线程直接结束了,果不其然,在加上thread.join()得到了预期结果。
如果是写在main方法是不存在这个问题的,但是单测的确存在这个问题。
原始代码:
- @Test
- public void multipleThreadTest(){
- System.out.println(Thread.currentThread().getName());
- LockThread[] lockThreads = new LockThread[10];
- for (int i=0;i< lockThreads.length;i++){
- lockThreads[i] = new LockThread(new ZkNodeNoneBlockingLock("app"));
- }
- for (LockThread lockThread : lockThreads) {
- lockThread.start();
- }
- }
-
- private static class LockThread extends Thread{
- ZkNodeNoneBlockingLock locker;
- public LockThread(ZkNodeNoneBlockingLock locker){
- this.locker = locker;
- }
- @Override
- public void run() {
- boolean lock = locker.lock();
- System.out.println(this.getName() + (lock ? "上锁成功" : "上锁失败"));
- }
- }
修改后代码:
- @Test
- public void multipleThreadTest(){
- System.out.println(Thread.currentThread().getName());
- LockThread[] lockThreads = new LockThread[10];
- for (int i=0;i< lockThreads.length;i++){
- lockThreads[i] = new LockThread(new ZkNodeNoneBlockingLock("app"));
- }
- for (LockThread lockThread : lockThreads) {
- lockThread.start();
- }
- for (LockThread lockThread : lockThreads){
- try {
- lockThread.join();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- private static class LockThread extends Thread{
- ZkNodeNoneBlockingLock locker;
- public LockThread(ZkNodeNoneBlockingLock locker){
- this.locker = locker;
- }
- @Override
- public void run() {
- boolean lock = locker.lock();
- System.out.println(this.getName() + (lock ? "上锁成功" : "上锁失败"));
- }
- }
thread.join()是当前线程,也就是main线程要等到thread线程执行完成才能继续往后执行。