簡體   English   中英

Java多線程演示無法正常工作

[英]Java Multiple Threads Demo not Working

我正在編寫一個小程序,以了解如何在Java中運行多個線程。 不知道為什么我沒有得到任何輸出:

class NuThread implements Runnable {
    NuThread() {
        Thread t = new Thread(this, "NuThread");
        t.start();
    }

    public void run() {
        try {
                for (int i=0; i<5; i++) {
                Thread th = Thread.currentThread();
                System.out.println(th.getName() + ": " + i);
                Thread.sleep(300);
            }
        } catch (InterruptedException e) {
            Thread th = Thread.currentThread();
            System.out.println(th.getName() + " interrupted.");
        }
    }
}

public class MultiThreadDemo {
    public static void main(String[] args) {
        NuThread t1, t2, t3;
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            System.out.println("Main interrupted.");
        }   
    }
}

您不是在創建NuThread對象。 這就是線程未啟動的原因。

在構造函數中啟動線程不是最好的主意,請參見此處

您沒有創建任何NuThread實例。 這行:

NuThread t1, t2, t3;

...僅聲明三個變量。 它不會創建任何實例。 您將需要以下內容:

NuThread t1 = new NuThread();
NuThread t2 = new NuThread();
NuThread t3 = new NuThread();

話雖如此,讓構造函數啟動一個新線程本身有點奇怪……最好將其刪除,而只需:

// TODO: Rename NuThread to something more suitable :)
NuThread runnable = new NuThread();
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
Thread t3 = new Thread(runnable);
t1.start();
t2.start();
t3.start();

請注意,可以對所有三個線程使用相同的Runnable ,因為它們實際上並不使用任何狀態。

暫無
暫無

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

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