java currentThread方法

实例代码

线程类

package mythread;

public class CountOperate extends Thread {

	public CountOperate() {
		System.out.println("CountOperate---begin");
		System.out.println("Thread.currentThread().getName()="
				+ Thread.currentThread().getName());
		System.out.println("this.getName()=" + this.getName());
		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("this.getName()=" + this.getName());
		System.out.println("run---end");
	}

}

测试类

package test;

import mythread.CountOperate;

public class Run {

	public static void main(String[] args) {
		CountOperate c = new CountOperate();
		Thread t1 = new Thread(c);
		t1.setName("A");
		t1.start();
	}

}

/*
output:

CountOperate---begin
Thread.currentThread().getName()=main
this.getName()=Thread-0
CountOperate---end
run---begin
Thread.currentThread().getName()=A
this.getName()=Thread-0
run---end 
*/

Thread.currentThread().getName()在两种实现线程的方式中都可以用

this.getName()只能在继承方式中使用。因为在Thread子类中用this,this代表的是线程对象。

如果你在Runnable实现类中用this.getName(),那么编译错误,因为在Runnable中,不存在getName方法

个人注解:Thread.currentThread().getName()获取得到的是当前线程的名字。this.getName()也是得到当前线程的名字,但是这个名字是属于某个线程的。

Thread t1 = new Thread(c);这个行为也只是把自定义线程c的执行权限交给t1。所以Thread.currentThread().getName()和this.getName()是不一样的。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部