synchronized修饰方法

synchronized 修饰普通方法相当于

synchronized(this){
	// 操作
}

synchronized 修饰静态方法

synchronized(C.class){
	// 操作
}

非线程安全举例

public class ApplicationDemo08 {

    public static void main(String[] args) throws InterruptedException {
        Thread thread;
        Runnable t;
        for(int j = 0; j < 100; j++){
            long start = System.currentTimeMillis();
            // i 的最大值,代表启动线程数
            for(int i = 0; i < 100; i++){
                t = new C();
                thread = new Thread(t);
                thread.start();
            }
            long end = System.currentTimeMillis();
            System.out.println("时间: " + (end - start));
            Thread.sleep(500);
            System.out.println("----" + C.count);
            C.count = 0;
        }
    }
}

class C implements Runnable{
    public static int count = 0;

	// 线程不安全情况
    public synchronized void add(){
        count ++;
    }
    
    // 线程安全情况
	// public synchronized static void add(){
    //     count ++;
    // }

    @Override
    public void run() {
        this.add();
    }
}

打印结果:(线程创建数自己修改测试)
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章