join的使用
作用:保证线程执行结果的可见性
/**
* @Author: wy
*/
public class MyThread {
private static Integer i = 1;
private static Integer j = 2;
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
i=j+1;
j=i;
});
Thread thread2 = new Thread(() -> {
i=3;
j=i;
});
thread1.start();
thread2.start();
Thread.sleep(100);
System.out.println("i:"+i);
System.out.println("j:"+j);
}
}
在以上代码中,按照理想状态如果thread1和thread2按着顺序执行的话,我们的到的结果应该是i=4,j=4。
但是我们知道,我们只是执行了start方法,并不代表线程开始运行,不会立即执行run方法。
此时线程只不过是成为就绪状态,到底哪个线程执行还是要取决于操作系统的调度算法。(window中是抢占式,即哪个线程抢用到cpu后知道线程执行完毕才会释放资源。
linux中为分