Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java多线程演示不工作_Java_Multithreading - Fatal编程技术网

Java多线程演示不工作

Java多线程演示不工作,java,multithreading,Java,Multithreading,我正在编写一个小程序,看看如何在Java中运行多个线程。不确定为什么我没有得到任何输出: class NuThread implements Runnable { NuThread() { Thread t = new Thread(this, "NuThread"); t.start(); } public void run() { try { for (int i=0; i<5;

我正在编写一个小程序,看看如何在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(){
螺纹t=新螺纹(该“螺母螺纹”);
t、 start();
}
公开募捐{
试一试{

对于(inti=0;i您没有创建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
是可以的,因为它们实际上不使用任何状态。

谢谢!这是Herbert Schildt的书中创建线程的方式,尽管我确实觉得你有一个观点。其他的东西(main?)应该是创建和运行线程。