Voletile-多线程小例子

public class Test{
public static volatile int t = 0;
//如果没有下面的全局锁标识,则结果不一定为10*1000
public static String lock="1";
public static void main(String[] args){

Thread[] threads = new Thread[10];
for(int i = 0; i < 10; i++){
//每个线程对t进行1000次加1的操作
threads[i] =new Thread(new Runnable(){

//或者把锁对象放在这里

//public String lock="1";
@Override
public void run(){
//如果没有下面的锁标识,则结果不一定为10*1000
synchronized (lock) {
for(int j = 0; j < 1000; j++){
t = t + 1;
}
}

}
});
threads[i].start();
}

//等待所有累加线程都结束
while(Thread.activeCount() > 1){
Thread.yield();
}

//打印t的值
System.out.println(t);
}
}

原文地址:https://www.cnblogs.com/javahepeng/p/12202135.html