我开始学习线程。我尝试过不同类型的线程创建。从下面的代码中可以看到线程 t4,目标是 Mythread1 的新实例,线程名称是“Thread4”。
但是当我看到输出时,我找不到线程名称“Thread 4”,而是得到了名称“Thread-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 线程5 线程22 线程5 线程33