先看代码
public class TwoThread extends Thread{ private Thread creatorThread; public TwoThread(){ //对调用本方法的线程进行记录 creatorThread = Thread.currentThread(); } public void run(){ for(int i=0; i<10; i++){ System.out.println("run"); printMsg(); } } public void printMsg(){ //对运行这一方法线程的引用 Thread t = Thread.currentThread(); if(t == creatorThread){ System.out.println("Creator Thread -- " + t.getName()); }else if(t == this){ System.out.println("New Thread -- " + t.getName()); }else{ System.out.println("Mystery Thread -- " + t.getName()); } } public static void main(String[] args){ TwoThread tt = new TwoThread();//调用构造方法,哪个线程调用?因为tt是由main线程创建所以由main线程调用构造方法? tt.start(); for(int i=0; i<10; i++){ System.out.println("main"); tt.printMsg();//main线程调用 } } }
本程序先由main线程对tt线程进行创建,对tt线程进行创建的过程中由main线程调用其构造方法,则creatorThread是对main线程的引用。第29行对tt.printMsg()也是由main线程进行调用,与tt对象无关。
则打印结果为
main Creator Thread -- main main Creator Thread -- main main Creator Thread -- main main Creator Thread -- main main Creator Thread -- main main Creator Thread -- main main Creator Thread -- main main Creator Thread -- main main Creator Thread -- main main Creator Thread -- main run New Thread -- Thread-0 run New Thread -- Thread-0 run New Thread -- Thread-0 run New Thread -- Thread-0 run New Thread -- Thread-0 run New Thread -- Thread-0 run New Thread -- Thread-0 run New Thread -- Thread-0 run New Thread -- Thread-0 run New Thread -- Thread-0
本文出自 “混混” 博客,请务必保留此出处http://yimaoqian.blog.51cto.com/1328422/1393081