Java运行3个线程并显示ID
我想运行多个java线程并通过输出显示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
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()
。