/** * */ public class TwoThread extends Thread { private Thread creatorThread; public TwoThread(){ creatorThread = Thread.currentThread(); } public void run(){ for(int i=0; i<5; i++){ printMsg(); } } public void printMsg(){ Thread t = Thread.currentThread(); if(t==creatorThread){ System.out.println("Creator thread"); } else if(t==this){ System.out.println("New thread"); } } /** * @param args */ public static void main(String[] args) { TwoThread tt = new TwoThread(); tt.start(); for(int i=0; i<10; i++){ tt.printMsg(); } } }
大家好,该程序在调用tt.start()方法时为什么没有直接去调用run()方法,而是执行完for循环后才调用的run()方法?
你的main方法执行是一个线程,你的那个自定义线程start,是另外一个线程,当main这个线程启动后,再启动你的自定义线程,从这个时候开始没有说哪个个线程就该先执行。
其实方法的执行顺序是不确定的,你多执行几次就知道了
[code="java"]
New thread
Creator thread
New thread
Creator thread
New thread
Creator thread
New thread
Creator thread
New thread
Creator thread
Creator thread
Creator thread
Creator thread
Creator thread
Creator thread
[/code]
这是我运行的输出
[quote]大家好,该程序在调用tt.start()方法时为什么没有直接去调用run()方法,而是执行完for循环后才调用的run()方法?[/quote]
你不能设定到底那个先运行,那个后运行,这个与具体的系统底层也有关系的,你只能保证,这个线程确实要开始运行了。