簡體   English   中英

Java線程-按順序調用線程

[英]Java Threads - Call threads in order

我希望線程按順序打印出它們的名稱。 輸出應如下所示:Thread-0
線程1
線程2
線程3
線程4
線程5
線程1
線程2
線程3

public class NameOutput extends Thread {
    static final int N = 5;
    static int activeThread = 0;

    public static void main(String[] args){

        for (int i = 1; i <= N; i++) {
            new NameOutput().start();
        }
    }

    @Override
    public void run(){
        while(true){
            this.printThreadName();
        }

    }
    private synchronized void printThreadName(){
        String threadName = "Thread-"+ activeThread;
        //Check if thread is in the right order
        if(!threadName.equals(this.getName())){
            try{
                wait();
            }catch (InterruptedException e){
                System.out.println(this.getName()+" was interrupted!");
            }
        }else{
            System.out.println(this.getName());
            activeThread = (activeThread + 1) % N;
            notifyAll();
        }
    }
}

不知何故,如果首先選擇了Thread-0,那么輸出就是Thread-0。 在第一個線程等待之后,程序停止。

問題是您創建了多個NameOutput ,並且它們使用了自己的監視程序鎖 ,這意味着它們之間將沒有“通信”(信號)。

相反,您需要共享監視器鎖定:

public class NameOutput extends Thread {
    static final int N = 5;
    static int activeThread = 0;
    static final Object lock = new Object(); // shared monitor lock

    public static void main(String[] args){

        for (int i = 1; i <= N; i++) {
            new NameOutput().start();
        }
    }

    @Override
    public void run(){
        while(true){
            this.printThreadName();
        }

    }
    private void printThreadName(){
        synchronized (lock) {
            String threadName = "Thread-"+ activeThread;
            //Check if thread is in the right order
            if(!threadName.equals(this.getName())){
                try{
                    lock.wait();
                }catch (InterruptedException e){
                    System.out.println(this.getName()+" was interrupted!");
                }
            }else{
                System.out.println(this.getName());
                activeThread = (activeThread + 1) % N;
                lock.notifyAll();
            }
        }
    }
}

另一個問題, wait 應該總是在while循環中使用,您可以做更多的事情:

private void printThreadName(){
    synchronized (lock) {
        while (!("Thread-"+ activeThread).equals(this.getName())) {
            try{
                lock.wait();
            }catch (InterruptedException e){
                System.out.println(this.getName()+" was interrupted!");
            }
        }
        System.out.println(this.getName());
        activeThread = (activeThread + 1) % N;
        lock.notifyAll();
    }
}

輸出:

Thread-0
Thread-1
Thread-2
Thread-3
Thread-4
Thread-0
Thread-1
Thread-2
Thread-3

暫無
暫無

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

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