测试案例
------------------------------------------------------------测试类------------------------------------------------------------
1 package com.qf.test; 2 3 /** 4 * @author qf 5 * @create 2018-09-20 15:32 6 */ 7 public class Run { 8 static int count = 0; 9 public static void main(String[] args) { 10 Thread thread = new Thread(new Runnable() { 11 @Override 12 public void run() { 13 for (int i = 0; i < 10; i++) { 14 count++; 15 } 16 } 17 }); 18 thread.start(); 19 System.out.println("count = " + count); 20 } 21 }
-----------------------------------------------------------打印结果-----------------------------------------------------------
count = 0
结果是0,并没有被修改成10,说明main线程在thread线程之前执行完成了
如何获取修改后的count值?使用join方法
------------------------------------------------------------测试类------------------------------------------------------------
1 package com.qf.test; 2 3 /** 4 * @author qf 5 * @create 2018-09-20 15:32 6 */ 7 public class Run { 8 static int count = 0; 9 public static void main(String[] args) throws InterruptedException { 10 Thread thread = new Thread(new Runnable() { 11 @Override 12 public void run() { 13 for (int i = 0; i < 10; i++) { 14 count++; 15 } 16 } 17 }); 18 thread.start(); 19 thread.join(); 20 System.out.println("count = " + count); 21 } 22 }
-----------------------------------------------------------打印结果-----------------------------------------------------------
count = 10
原因分析
join源码
public final void join() throws InterruptedException {
join(0);
}
==============================================================================
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {// thread对象调用的isAlive方法,所以只要thread还存活,就会循环
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);// wait方法,使当前线程等待,当前线程是main线程
now = System.currentTimeMillis() - base;
}
}
}
join方法使得当前线程进入阻塞状态,进入排队队列的作用,且必须等待调用join的线程对象执行完run方法才能执行