1. 程式人生 > >多線程(二)多線程安全與同步

多線程(二)多線程安全與同步

一個數 最終 鎖對象 inf 線程安全問題 pan 安全問題 rgs 同步方法

一,環境

idea

二.什麽是線程安全問題,為什麽會有線程安全問題

線程安全問題產生於多個線程同時訪問共享資源(通常查詢不會產生)

三.舉例

假如我現在想講一個數循化加一,最終增加到1000.但是需要用5個線程來加

class Count implements Runnable{
    private int count=1;

    public void run() {
        while (count<=1000){
            count=count+1;
            System.out.println(Thread.currentThread().getName()
+",count:"+count); } } } public class ThreadTest { public static void main(String[] args) { Count count=new Count(); Thread t1=new Thread(count,"線程一"); Thread t2=new Thread(count,"線程二"); Thread t3=new Thread(count,"線程三"); Thread t4=new Thread(count,"線程四"); Thread t5
=new Thread(count,"線程五"); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); } }

結果:

技術分享圖片

代碼顯示:最多會增加到1000循環就會結束那麽為什麽會出現1001呢!!

由於現在是多線程增加,有可能當count增加到999的時候同時又兩個線程都進入了while循環裏,然後就連續增加了兩次

那麽怎麽解決呢!!!

四.使用鎖來解決

4.1同步代碼塊

class Count implements Runnable{
    
private volatile int count=1; private static Object oj = new Object(); public void run() { while (count<=1000){ synchronized (oj) {//oj就是鎖對象可以為任意對象也可為this if(count<=1000) { count = count + 1; System.out.println(Thread.currentThread().getName() + ",count:" + count); } } } } } public class ThreadTest { public static void main(String[] args) { Count count=new Count(); Thread t1=new Thread(count,"線程一"); Thread t2=new Thread(count,"線程二"); Thread t3=new Thread(count,"線程三"); Thread t4=new Thread(count,"線程四"); Thread t5=new Thread(count,"線程五"); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); } }

4.2使用同步方法

class Count implements Runnable{
    private volatile int  count=1;
    private static Object oj = new Object();

    public void run() {
        while (count<=1000){
            
            sole();
               
            }
        

    }
    public synchronized void sole(){//這把鎖的鎖對象就是this
        if(count<=1000) {
            count = count + 1;
            System.out.println(Thread.currentThread().getName() + ",count:" + count);
        }
    }
}
public class ThreadTest {
    public static void main(String[] args) {
        Count  count=new Count();
        Thread t1=new Thread(count,"線程一");
        Thread t2=new Thread(count,"線程二");
        Thread t3=new Thread(count,"線程三");
        Thread t4=new Thread(count,"線程四");
        Thread t5=new Thread(count,"線程五");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }

}

多線程(二)多線程安全與同步