java 线程 test
import org.junit.Test;
public class testThread {
@Test
public void testThreads() throws Exception {
Thread add = new AddThread();
Thread dec = new DecThread();
dec.start();
add.start();
add.join();
dec.join();
System.out.println(Counter.count+"ss");
}
}
class Counter {
public static final Object lock = new Object();
public static int count = 0;
}
class AddThread extends Thread {
public void run() {
for (int i=0; i<10000; i++) {
synchronized (Counter.lock) {
Counter.count += 1;
}
}
System.out.println(Counter.count);
}
}
class DecThread extends Thread {
public void run() {
for (int i=0; i<10000; i++) {
synchronized(Counter.lock) {
Counter.count += 1;
}
}
System.out.println(Counter.count);
}
}
13063
20000
20000ss
得出结论,只有在synchronized内 线程变量才是安全的。
本文来自博客园,作者:给香菜送点香菜,转载请注明原文链接:https://www.cnblogs.com/mingkewang/p/17218226.html

浙公网安备 33010602011771号