1. 程式人生 > >多執行緒不加鎖會出現錯誤

多執行緒不加鎖會出現錯誤

這是一個會出現錯誤的程式,原本設想的是能夠通過多執行緒操作,實現一個標誌的遞減,在關鍵地方新增Thread.Sleep()函式,就可以模仿不加鎖出現的錯誤


public class RunableDemo {
    public static void main(String[] args)
    {
        MyThread t=new MyThread();

        Thread t1=new Thread(t);
        Thread t2=new Thread(t);
        Thread t3=new Thread(t);


        t1.start();;
        t2.start();
        t3.start();
    }
}

class MyThread implements Runnable
{
    private int flag=100;
    @Override
    public void run()
    {
        while(flag>0)
        {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //這裡是為了演示多個執行緒同時執行一個程式產生的錯誤
//            很容易出現輸出-1這種錯誤,所以以後就要學會加鎖 。日後再學
            System.out.println(Thread.currentThread().getName()+"..."+flag);
            flag--;
        }
    }
}

這裡是結果


Thread-0...100
Thread-1...100
Thread-2...100
Thread-1...97
Thread-0...96
Thread-2...96
Thread-0...94
Thread-2...93
Thread-1...92
Thread-2...91
Thread-0...91
Thread-1...91
Thread-2...88
Thread-1...87
Thread-0...86
Thread-2...85
Thread-1...84
Thread-0...84
Thread-2...82
Thread-0...81
Thread-1...80
Thread-2...79
Thread-1...78
Thread-0...77
Thread-2...76
Thread-0...75
Thread-1...75
Thread-2...73
Thread-0...72
Thread-1...71
Thread-2...70
Thread-1...69
Thread-0...69
Thread-2...67
Thread-1...66
Thread-0...66
Thread-2...64
Thread-1...63
Thread-0...62
Thread-2...61
Thread-0...60
Thread-1...60
Thread-2...58
Thread-0...57
Thread-1...57
Thread-2...55
Thread-0...54
Thread-1...54
Thread-2...52
Thread-1...51
Thread-0...51
Thread-2...49
Thread-1...48
Thread-0...48
Thread-2...46
Thread-1...45
Thread-0...45
Thread-2...43
Thread-0...42
Thread-1...42
Thread-2...40
Thread-0...39
Thread-1...39
Thread-2...37
Thread-0...36
Thread-1...36
Thread-2...34
Thread-0...33
Thread-1...33
Thread-2...31
Thread-0...30
Thread-1...30
Thread-2...28
Thread-0...27
Thread-1...27
Thread-2...25
Thread-0...24
Thread-1...24
Thread-2...22
Thread-1...21
Thread-0...21
Thread-2...19
Thread-0...18
Thread-1...17
Thread-2...16
Thread-1...15
Thread-0...15
Thread-2...13
Thread-1...12
Thread-2...11
Thread-0...11
Thread-1...9
Thread-0...8
Thread-2...8
Thread-1...6
Thread-0...5
Thread-2...4
Thread-1...3
Thread-2...2
Thread-0...1
Thread-1...0
Thread-2...-1

不僅會出現重複的數字,甚至會出現-1