線程---同步解決線程的安全問題

class Demo implements Runnable {
    //創建同步所需對象
    Object obj = new Object();
    int num = 100;

    public void run(){
        while(true){
            //創建同步解決線程的安全問題,同步加在使用共享數據的代碼快上
            synchronized(obj){
            if(num>0){
                try{Thread.sleep(6);}catch(InterruptedException e){
                    
                }
                System.out.println(Thread.currentThread().getName()+"---"+num);
                num--;
            }
        
            }
        }
    }
}

public class XianCheng {
    public static void main(String[] args) {
        Demo d=new Demo();
        Thread th=new Thread(d);
        Thread th1=new Thread(d);
        Thread th2=new Thread(d);
        th.start();
        th1.start();
        th2.start();
    }
}

兩個線程,在兩個不同的方法上進行

class Demo implements Runnable {
    int num = 100;
    boolean flag = true;

    public void run() {
        if (flag == true) {
            while (true) {
                synchronized (this) {
                    if (num > 0) {
                        System.out.println(Thread.currentThread().getName() + "---" + num);
                        num--;
                    }

                }
            }
        } else {
            show();
        }
    }

    //當方法里的代碼都需要加同步,就可以 在方法上加同步,非靜態方法加同步,同步鎖使用的是當前對象
    //當在靜態方法上加同步時,同步鎖是類名加class
    private synchronized void show() {
        // TODO Auto-generated method stub
        if (num > 0) {
            System.out.println(Thread.currentThread().getName() + "---" + num);
            num--;
        }
    }
}

public class XianCheng {
    public static void main(String[] args) {
        Demo d = new Demo();
        Thread th1 = new Thread(d);
        Thread th2 = new Thread(d);
        th1.start();
        //由于cpu先是在主線程上運行的,當開啟第一個線程時cpu不一定立刻執行
        //這時加一個“睡眠”,保證cpu進入第一個線程
        try{Thread.sleep(6);}catch(InterruptedException e){
            
        }
        th2.start();
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容