- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
public class GetCurrentThread implements Runnable { Thread th; public GetCurrentThread(String
有没有办法从 ThreadId 获取线程的 ThreadName? (例如,ThreadID,例如 10 或 15 等) 最佳答案 不在托管代码中。您甚至无法获得 Thread 的列表据我所知,当前进
我正在尝试配置 log4j2 配置以通过线程名称将消息路由到多线程程序的不同日志文件。 到目前为止,这是我所拥有的(与 log4j2 配置相关): |-/src/main/java/log4j2/pl
我有如下 NLog 配置。 如果存在,它会打印线程的名称。否则我会得到空字符串而不是线程名称。 问题:我如何存档下面的行为? 如果线程有名称 - 打印线程名称 否则 - 打印 ManagedThrea
我是一名优秀的程序员,十分优秀!