最轻量的同步
volatile 关键字通常使用在一次写,多次读的场景,使线程之间可以实时拿到更新的结果,但多次写却不能保证实时拿到
package test;
public class ThreadJoinTest {
private static class Count extends Thread{
private ThreadJoinTest simplOper;
Object obj = new Object();
public Count(ThreadJoinTest simplOper){
this.simplOper = simplOper;
}
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
simplOper.add1();
}
}
}
volatile int count =0;
public static void main(String[] args) {
ThreadJoinTest tjt =new ThreadJoinTest();
Count c1= new Count(tjt);
Count c2= new Count(tjt);
c1.start();
c2.start();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(tjt.count);
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容