admin管理员组

文章数量:1612099

文章目录

  • 一、currentThread方法
    • 1.例一
    • 2.例二
    • 3.例三
    • 4.例四

一、currentThread方法

返回当前正在执行的线程对象,需要注意普通对象调用currentThread方法不是线程对象调用currentThread的情况。

1.例一

public class Test {
	
	public static void main(String[] args) {
		System.out.println(new Thread().currentThread());//currentThread()方法返回一个线程,哪个线程执行这行代码,返回哪个线程
	}
}

执行结果

import java.util.Date;

public class Test {
	
	public static void main(String[] args) {
		TimeThread timeThread = new TimeThread();//创建时间线程
		timeThread.start();//时间线程就绪
		System.out.println(timeThread);//打印时间线程
	}
}

class TimeThread extends Thread{
	@Override
	public void run() {
		System.out.println(this);//打印时间线程
		System.out.println(new Thread().currentThread());//时间线程执行这行代码,返回时间线程
	}
}

执行结果

2.例二

import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {

	public static void main(String[] args) {
		TimeThread timeThread = new TimeThread();//创建时间线程
		new TimeThread().start();//时间线程就绪,时间线程执行run方法,调用currentThread方法的线程为时间线程
		timeThread.run();//timeThread对象调用run方法,故调用currentThread方法的线程仍为主线程
	}
}

class TimeThread extends Thread{

	public TimeThread(){
		super("时间线程");//给线程命名
	}
	
	@Override
	public void run() {
		printTime();//调用方法
	}
	
	public void printTime(){
		Thread thread = Thread.currentThread();
		String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
		System.out.println(thread.getName()+",当前时间:"+time);
	}
}

执行结果

3.例三

public class Test {

	public static void main(String[] args) {
		TimeThread timeThread = new TimeThread();//创建了一个时间线程对象
		System.out.println("########"+timeThread);//打印该时间线程对象
		timeThread.start();//时间线程就绪,获取到CPU资源的使用权,故currentThread方法返回的是时间线程对象
		//由于线程执行过程是抢占式的,所以只有获取到CPU资源的时候线程才进入运行状态执行输出,故代码执行的顺序不会完全的自上而下
		timeThread.run();//主线程中的timeThread对象调用run方法,故currentThread返回的是主线程对象
	}
}

class TimeThread extends Thread{

	@Override
	public void run() {
		Thread thread = Thread.currentThread();//什么线程调用中国方法就返回什么线程对象
		System.out.println("@@@@@@@@"+thread);
	}
}

执行结果

4.例四

public class Test {

	public static void main(String[] args) {
		TimeThread timeThread = new TimeThread();//创建了一个时间线程对象
		System.out.println("########"+timeThread);//打印该时间线程对象
		timeThread.start();//使得该时间线程对象处于就绪状态,时间线程对象调用run方法中的main方法中的currentThread方法
		//故返回的thread是时间线程对象,打印输出的也是时间线程对象
		
		timeThread.main();//timeThread对象调用main方法,此时timeThread对象只是一个普通的对象不是线程对象
		//故调用这个方法的线程仍为主线程,currentThread方法返回的是一个主线程对象
	}
}

class TimeThread extends Thread{

	@Override
	public void run() {
		main();
	}
	
	void main(){
		Thread thread = Thread.currentThread();
		System.out.println("@@@@@@@@"+thread);
	}
}

执行结果

本文标签: 如何正确过程程序方法currentThread