簡體   English   中英

Java中的線程

[英]Threads in Java

我已經創建了一個簡單的程序來測試Java中的Threads。 我想要它無限打印我的數字,如123123123123123.Dunno為什么,但目前它只停止一個周期后完成213。 誰知道為什么?

public class Main {
    int number;

    public Main(int number){
    }

    public static void main(String[] args) {
        new Infinite(2).start();
        new Infinite(1).start();
        new Infinite(3).start();
    }
}

class Infinite extends Thread {
    static int which=1;
    static int order=1;
    int id;
    int number;
    Object console = new Object();

    public Infinite(int number){
        id = which;
        which++;
        this.number = number;
    }

    @Override
    public void run(){
        while(1==1){
            synchronized(console){
                if(order == id){
                    System.out.print(number);
                    order++;
                    if(order >= which){
                        order = 1;
                    }
                    try{
                        console.notifyAll();
                        console.wait();
                    }
                    catch(Exception e)
                    {}                    
                }
                else {
                    try{
                        console.notifyAll();
                        console.wait();
                    }
                    catch(Exception e)
                    {}                    
                }
            }
            try{Thread.sleep(0);} catch(Exception e) {}
        }
    }
}

每個Infinite實例都在同步,然后在其自己的console對象上等待通知。 一旦線程進入console.wait() ,它就不會繼續。

你似乎希望它們都在同一個對象上同步 - 所以你需要,例如,使console靜態。

重新阻塞的線程可能等待獲取監視器以調用wait。 您沒有正確使用等待通知機制。

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#wait%28%29

每個線程正在同一個不同的對象上進行同步。 當控制轉到console.wait()時,執行線程將等待另一個線程調用控制對象上的notify()/ notifyAll()。 沒有其他線程正在執行此操作,因為每個線程都有自己的控件對象副本。 因此,所有線程在打印一次后無限期地等待。 要解決此問題,請保留所有線程可以等待的公共對象。

請記住, System.out.print(..)不會自動刷新輸出。

另外,看看java.util.concurrent.Semaphore 您可能能夠執行您正在嘗試的操作(按預定義的順序執行線程),而無需同步和調用等待。

暫無
暫無

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

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