Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.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运行3个线程并显示ID_Java_Multithreading - Fatal编程技术网

Java运行3个线程并显示ID

Java运行3个线程并显示ID,java,multithreading,Java,Multithreading,我想运行多个java线程并通过输出显示ID。现在我的代码似乎只创建一个线程并多次调用它。请帮我找出问题所在 我的班级: public class MyThreads extends Thread {​​ public void run() {​​ Thread t = new Thread(); t.start(); System.out.println("Running - ID "+t.currentThr

我想运行多个java线程并通过输出显示ID。现在我的代码似乎只创建一个线程并多次调用它。请帮我找出问题所在

我的班级:

public class MyThreads extends Thread {​​


    public void run() {​​

        Thread t = new Thread();

        t.start();

        System.out.println("Running - ID "+t.currentThread().getId());

    }​​
}​​


public class MyClass {​​
    public static void main(String[] args) {​​

        MyThreads thread1 = new MyThreads();

        MyThreads thread2 = new MyThreads();

        MyThreads thread3 = new MyThreads();

        thread1.run();

        thread2.run();

        thread3.run();
}​​

您所做的是,在“MyThreads”类的run方法中启动一个新线程,然后调用
System.out.println(“Running-ID”+t.currentThread().getId())
只会给你主线程的ID,因为你的run方法是在主线程上执行的,因为它从来没有作为一个新线程正确启动过。这有点难以解释,您应该阅读更多关于如何正确调用和处理java线程的内容

下面的代码将实现您希望执行的操作

public class MyThreads extends Thread {​​

    @Override
    public void run() {​​
        System.out.println("Running - ID "+Thread.currentThread().getId());

        System.out.println("Running - ID "+this.getId());
    }​​
}​​


public class MyClass {​​
public static void main(String[] args) {​​

    MyThreads thread1 = new MyThreads();

    MyThreads thread2 = new MyThreads();

    MyThreads thread3 = new MyThreads();

    thread1.start();

    thread2.start();

    thread3.start();
}​​ 

尝试将打印更改为
t.getId()