最近经常为公司面试新人,问了一个简单的线程问题,许多培训机构也都出过这种练习题,题目如标题
package thread;/** * 线程类 * @author zy * */public class ExecutorThread{ /** * 标志子线程调用方法是否被调用 */ PRivate boolean mainIsRunning = false; /** * 子线程调用方法 */ public synchronized void sub(){ while(mainIsRunning){//如果子线程方法没被调用,即调用了主线程执行 //等待别的线程使用 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for(int i = 0 ;i<10;i++){ System.out.println("sub:" + i); } mainIsRunning = true; //唤醒别的在等待的线程 this.notify(); } /** * 主线程调用方法 */ public synchronized void main(){ while(!mainIsRunning){//如果主线程没被调用,即子线程执行 try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int i = 0 ;i<100;i++){ System.out.println("main:" + i); } mainIsRunning = false; this.notify(); }}package thread;public class ExecutorThreadTest { public static void main(String[] args) { final ExecutorThread thread = new ExecutorThread(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 50; i++) { System.out.println("sub is " + i + " count"); thread.sub(); } } }).start(); for (int i = 0; i < 50; i++) { System.out.println("main is " + i + " count"); thread.main(); } }}能运行通过试问,如果我把代码修改成这样还能正常运行么?为什么
package thread;/** * 线程类 * @author zy * */public class ExecutorThread{ /** * 标志子线程调用方法是否被调用 */ private boolean mainIsRunning = false; /** * 子线程调用方法 */ public synchronized void sub(){ for(int i = 0 ;i<10;i++){ System.out.println("sub:" + i); } mainIsRunning = true; //唤醒别的在等待的线程 this.notify(); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 主线程调用方法 */ public synchronized void main(){ for(int i = 0 ;i<100;i++){ System.out.println("main:" + i); } mainIsRunning = false; this.notify(); try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
新闻热点
疑难解答