簡體   English   中英

Java中產生2個線程的多線程

[英]multithreading in Java with 2 threads spawned

我在Java中編寫了一個多線程程序,如下所示: -

public class Client {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub


        Counter counter = new Counter();

        int val = counter.getValue();
        while(val < 5){
            val = counter.getValue();
            System.out.println("In main thread : "+val);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

}
}

class Counter implements Runnable {

    private int countValue;
    Counter(){
        countValue = 0;
        Thread thread = new Thread(this ,"Counter A");
        Thread thread1 = new Thread(this    ,"Counter B");
        thread.start();
        thread1.start();
    }

    int getValue(){
        return countValue;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while( countValue < 5){

                System.out.println("In child thread : "+ ++countValue );
                try {
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    }

}
}

程序輸出為:

In main thread : 0  
In child thread : 2   
In child thread : 1   
In child thread : 3  
In child thread : 3  
In child thread : 4  
In child thread : 5  
In main thread : 5  

誰能詳細解釋一下這個輸出是怎么來的。謝謝你提前

您有3個線程(主線程和2個子線程)都並行運行(除非有單個proc框),它們都在讀寫不受任何類型的同步保護的資源countValue

當您執行此類操作時,您將獲得明顯的隨機輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM