有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程Java多线程演示不工作

我正在写一个小程序,看看如何在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.");
        }   
    }
}

共 (2) 个答案

  1. # 1 楼答案

    你没有创建任何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,因为它们实际上不使用任何状态

  2. # 2 楼答案

    您没有创建NuThread的对象。这就是线程没有启动的原因

    在构造函数中启动线程不是最好的方法,请参见here