我开始学习线程。我尝试过不同类型的线程创建。从下面的代码你可以看到线程t4,目标是Mythread1的新实例&线程名称是“Thread4”。基本线程创建 - 线程名称不正确
但是,当我看到输出时,我无法找到线程名称“线程4”,而是获得名称“线程-4”。但是这是默认线程名称的命名约定。
我无法理解有什么问题。我相信它的基本错误。请纠正我。
class MyThread1 extends Thread {
MyThread1() {
}
public MyThread1(String nameIn) {
super(nameIn);
}
public void run() {
System.out.println(this.getName());
}
}
class MyThread2 implements Runnable {
Thread ownThread;
public MyThread2() {
}
public MyThread2(String nameIn) {
ownThread = new Thread(this, nameIn);
}
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public class ThreadCreation {
public static void main(String[] args) {
//Execution type1, as direct thread object
MyThread1 t1 = new MyThread1();
Thread t2 = new MyThread1();
Thread t3 = new Thread(new MyThread1());
Thread t4 = new Thread(new MyThread1(), "Thread4");
Thread t5 = new MyThread1("Thread5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
//Execution type2, pass the runnable object to thread constructor
Thread t11 = new Thread(new MyThread2());
Thread t22 = new Thread(new MyThread2(), "Thread22");
MyThread2 t33 = new MyThread2("Thread33");
t11.start();
t22.start();
t33.ownThread.start();
}
}
输出:
线程0 线程2 线程1 线程4 Thread5 Thread22 Thread5 Thread33
我明白了,不需要传递一个Thread类对象来代替一个可运行的对象。这创建了2个线程。谢谢。 –
它不会创建两个_native_线程,但它确实会创建两个Java'Thread'对象。只有一个从未开始。 – Gray