Thread.currentThread 和this 区别

本文通过一个具体示例详细解析了Java多线程编程中Thread.currentThread()和this的区别,阐述了线程状态、线程引用及线程启动过程,帮助读者深入理解多线程编程的核心概念。

笔者最近在看《java多线程编程核心技术》一书时,看到一个例子说明如何区分Thread.currentThread 和this ,特此分享。

例子如下:

package test;

public class CountOperate extends Thread {

	public CountOperate(){
	      
		System.out.println("CountOperate-----begin");
		System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
		System.out.println("Thread.currentThread().isAlive() = " + Thread.currentThread().isAlive());
		System.out.println("this.getName() = " + this.getName());
		System.out.println("this.isAlive() = " + this.isAlive());
		System.out.println("CountOperate-----end");
	}
	
	@Override
	public void run(){
		
		System.out.println("run-----begin");
		System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
		System.out.println("Thread.currentThread().isAlive() = " + Thread.currentThread().isAlive());
		System.out.println("this.getName() = " + this.getName());
		System.out.println("this.isAlive() = " + this.isAlive());
		System.out.println("run-----end");
	}
	
}



package test;

public class Run {

	public static void main(String[] args) {

		CountOperate c = new CountOperate();
		Thread t1 = new Thread(c);
		System.out.println("main begin t1 isAlive = " + t1.isAlive());
		t1.setName("A");
		t1.start();
		System.out.println("main end t1 isAlive = " + t1.isAlive());
	}

}

打印结果如下:

CountOperate-----begin
Thread.currentThread().getName() = main
Thread.currentThread().isAlive() = true
this.getName() = Thread-0
this.isAlive() = false
CountOperate-----end
main begin t1 isAlive = false
main end t1 isAlive = true
run-----begin
Thread.currentThread().getName() = A
Thread.currentThread().isAlive() = true
this.getName() = Thread-0
this.isAlive() = false
run-----end

结果分析:

首先

isAlive()判断线程是否处于活动状态,活动状态就是指线程已经启动,尚未终止。

其次,Thread t1 = new Thread(c);调用的是如下构造函数(jdk源码如下)

  /**
     * Allocates a new {@code Thread} object. This constructor has the same
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
     * {@code (null, target, gname)}, where {@code gname} is a newly generated
     * name. Automatically generated names are of the form
     * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
     *
     * @param  target
     *         the object whose {@code run} method is invoked when this thread
     *         is started. If {@code null}, this classes {@code run} method does
     *         nothing.
     */
    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }

本例中一共有三个线程

main  主线程

thread-0 : 也就是CoutOperate产生的线程

thread-1: 也就是“A”

提前说明一下:currentThread()方法返回的是代码段正在被哪个线程调用的信息

调用CountOperate产生结果:

CountOperate-----begin
Thread.currentThread().getName() = main
Thread.currentThread().isAlive() = true
this.getName() = Thread-0
this.isAlive() = false
CountOperate-----end

很好理解,main函数调用的CountOperate,所以Thread.currentThread()是main, 此时main肯定是活跃的(否则怎么调用别的线程呢),this肯定指的是当前类了,这个线程thread-0只是生成并没有被start或run所以isAlive是false;

main begin t1 isAlive = false
main end t1 isAlive = true

这个结果很好立即,请看Run()函数,这两个打印之间存在一个t1.start();代码,所以一个start之前是false,之后是true(也不一定,如果中间存在时间较长的话,t1就结束了,也可能是false)。

至于结果:

run-----begin
Thread.currentThread().getName() = A
Thread.currentThread().isAlive() = true
this.getName() = Thread-0
this.isAlive() = false
run-----end

是在t1进行start产生的,具体细节过程如下:

Thread对象进行start启动线程,我们直接启动的是Thread(Runnable target),所以c作为构造参数传给Thread中的属性target,之后,在Thread的run方法中,调用target.run(),此时Thread.currentThread()指的就是Thread的引用,也就是为什么这里Thread.currentThread()是A(thread-1)的原因了,而this依旧是myThread的引用,也就是说,this的这个线程还是thread-0,从这里可以看出二者区别了,值得注意的是笔者认为thread-0这个线程从头至尾一致没有执行过,就是说,这个的iaAlive一致是false,如果不对之处,请指正,感谢!

<think> Hmm, the user is asking about two lines of C# code related to thread naming and logging. From the code snippet, it seems they're working with multithreading in .NET, specifically setting the current thread's name and then writing thread info. The first line constructs a thread name using string interpolation, combining the managed thread ID with "UI_Dispatcher" - likely indicating this is the main UI thread. The second line triggers some logging mechanism. The user probably wants to understand why you'd do this and what practical purpose it serves. I recall that in debugging scenarios, naming threads makes stack traces and debugger output much more readable. When you have multiple threads, seeing "UI_Dispatcher #1234" is way better than just numbers. The ThreadInfoRecord.WriteInfo() part suggests they're dumping thread state - maybe for debugging deadlocks or performance issues. The user seems technically proficient - they're working at the Thread API level. But I should keep the explanation accessible since thread concepts can get complex. They might be debugging a tricky multithreading issue, given they're examining such low-level details. For the related questions, I'll focus on practical extensions: why name threads, what happens if you don't, how the logging works, and alternatives. These cover both the "what" and "why" behind the code. </think> 这两行代码的作用是: 1. `Thread.CurrentThread.Name = $"{Thread.CurrentThread.ManagedThreadId} UI_Dispatcher";` - 给当前执行线程命名:将托管线程ID拼接字符串"UI_Dispatcher"作为线程名称(例如:`"7 UI_Dispatcher"`) - 核心目的:标识UI调度线程,便于调试时识别主线程或关键线程 2. `ThreadInfoRecord.WriteInfo();` - 调用自定义方法记录线程信息(根据类名推断) - 典型实现可能包含: ```csharp class ThreadInfoRecord { public static void WriteInfo() { Debug.WriteLine($"Thread [{Thread.CurrentThread.Name}] State: {Thread.CurrentThread.ThreadState}"); // 可能记录堆栈跟踪/时间戳等 } } ``` - 作用:输出当前线程状态信息到日志或调试窗口,用于监控线程行为 **主要应用场景**: - 调试多线程程序时快速识别UI线程 - 跟踪线程生命周期状态变化 - 诊断线程阻塞或死锁问题
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值