java 线程 test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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);
    }
}<br><br>

13063
20000
20000ss 

 得出结论,只有在synchronized内 线程变量才是安全的。 

posted @   给香菜送点香菜  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示