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内 线程变量才是安全的。 

posted @ 2023-03-15 14:42  给香菜送点香菜  阅读(26)  评论(0)    收藏  举报