public class RunnableThreadExample implements Runnable { public int count = 0; public static void main(String[] args) { RunnableThreadExample instance = new RunnableThreadExample(); Thread thr = new Thread(instance); thr.start(); while(instance.count != 5) { try { Thread.sleep(500); System.out.println(" Within main method"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override public void run() { while(count < 5) { try { System.out.println("Sleeping for 500 seconds within run method"); Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } count++; } } }我注意到 Sys out within main 方法同時(shí)運(yùn)行,而 Sys out within run ( ) 方法被執(zhí)行。The output looks as follows:Sleeping for 500 seconds within run methodSleeping for 500 seconds within run method Within main methodSleeping for 500 seconds within run method Within main method Within main methodSleeping for 500 seconds within run methodSleeping for 500 seconds within run method Within main method Within main method Within main method當(dāng)我們調(diào)用 thr.start() 時(shí),不應(yīng)該在 run() 處完成執(zhí)行,然后回到 while(instance.count != 5) { ??
1 回答

慕沐林林
TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
不會(huì)從主線程調(diào)用您的run
方法。相反,創(chuàng)建一個(gè)新的執(zhí)行線程(獨(dú)立于主線程),并且該新線程執(zhí)行. 主線程將立即(無需等待新線程發(fā)生什么)恢復(fù) . 之后的下一條指令。start
run
start
這種并發(fā)正是您要使用Thread
.
添加回答
舉報(bào)
0/150
提交
取消