gpt4 book ai didi

java - 需要了解 thread(this, ThreadName) in java?

转载 作者:行者123 更新时间:2023-11-30 06:30:02 26 4
gpt4 key购买 nike

public class GetCurrentThread implements Runnable {
Thread th;

public GetCurrentThread(String threadName) {
th = new Thread(this,threadName); //<----DOUBT
System.out.println("get threadname "+th.getName());
th.start();
}

public void run() {
System.out.println(th.getName()+" is starting.....");
System.out.println("Current thread name : " + Thread.currentThread().getName());
}

public static void main(String args[]) {
System.out.println("Current thread name : " + Thread.currentThread().getName());
new GetCurrentThread("1st Thread");
//new GetCurrentThread("2nd Thread");
}
}

谁能解释一下上面代码的第二行是做什么的?我对“th = new Thread(this,threadName)”的理解是,它将创建具有给定名称的线程对象;假设名称为“第一个线程”。现在,“this”关键字在这里做什么?因为当我删除它并尝试获取线程的名称时,我得到了没有问题的名称,但它从未开始运行()。有人可以解释一下简单来说,而不是用一行答案。非常感谢大家的帮助。

最佳答案

th = new Thread(this, threadName); //<----DOUBT

您的第 2 行正在构造一个新的 Thread 对象,将您的 GetCurrentThread 类作为目标 (this) 并且线程名称为 “线程名称”。您的 this 可以作为目标,因为它实现了 Runnable。在 Thread 类内部,当线程启动时,它会调用 Thread.run(),它会执行以下操作:

public void run() {
if (target != null) {
target.run();
}
}

您的 GetCurrentThread 是目标,因为您将 this 传递给构造函数。实际上,它 应该被称为GetCurrentThread,因为它不是线程。构造完 Thread 后两行,开始运行:

th.start();

start() 方法执行创建单独工作 native 线程的实际工作。线程做的第一件事是调用 GetCurrentThread 类中的 run() 方法。

作为评论,通常建议类在其构造函数中start() 本身。这有一些固有的竞争条件可能会导致问题。最好在 GetCurrentThread

上有一个 start() 方法
/** start the underlying thread */
public void start() {
th.start();
}

你的主要看起来像:

public static void main(String args[]) {
System.out.println("Current thread name : " + Thread.currentThread().getName());
GetCurrentThread thread1 = new GetCurrentThread("1st Thread");
thread1.start();
}

关于java - 需要了解 thread(this, ThreadName) in java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10897361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com