package thread.name; import java.text.SimpleDateFormat; import java.util.Date; public class GetThreadName implements Runnable { //private int i=10; private boolean flag = true; @Override public void run() { while(flag){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); System.out.println("================"); } } public void stop(){ this.flag = false; } }
public class ThreadMain { /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub GetThreadName test = new GetThreadName(); Thread proxy1 = new Thread(test,"test1"); proxy1.start(); System.out.println(Thread.currentThread().getName()+"-proxy1-"); System.out.println("===================="); System.out.println(Thread.currentThread().getName()+"-main-"); System.out.println("===================="); test.stop(); System.out.println(Thread.currentThread().getName()); } }
为什么输出是
main-proxy1- ==================== main-main- ==================== main test1 ================
这段代码中线程的执行顺序是? 为什么最后一个main出现在test1 上面?
Thread.sleep(3000);本来是并行的,加了这个,当然是main先执行完。最后输出的是test1
因为Main线程中的代码很快就执行完了,而test1至少需要sleep 3秒,然后才能打印。另外这种情况下flag应该用volatile修饰保证可见性。
test1线程开始睡,main线程打印:
main-proxy1- ==================== main-main- ====================
main线程设置flag=false后test1线程还没醒,只有main一个可运行线程,main线程打印:
main
main线程结束
3秒之后test1线程睡醒了,打印:
test1 ================
第二次循环flag为false跳出循环,test1线程结束
另外这种情况下flag应该用volatile修饰保证可见性。