`
lc87624
  • 浏览: 143075 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

一道淘宝笔试题

阅读更多
题目大致如下:
	
public class ThreadTest {
	public static void main(String[] args) {
		System.out.println("start");
		new Thread(new Runnable(){
			public void run(){
				System.out.println("step2");
			}
		}).start();
		System.out.println("step1");
		new Thread(new Runnable(){
			public void run() {
				System.out.println("step3");
			}
		}).start();
		System.out.println("end");
	}
}


问:
1.输出是什么样的,为什么?
2.若要按start step1 step2 step3 end的顺序输出,应该如何修改

第一问不多说了
第二话答的时候只是狂扯了一通多线程的锁机制,具体实现没考虑,回来翻了下synchronized和notify、wait之类的用法之后,补充了一下修改的代码,如下:
public class ThreadTest {

	public static void main(String[] args) throws InterruptedException {
		
		final Object lock = new Object();
		synchronized(lock){
			System.out.println("start");
			new Thread(new Runnable(){
				public void run(){
					synchronized(lock){
						System.out.println("step2");
						lock.notify();
					}
				}
			}).start();
			System.out.println("step1");
			lock.wait();
			new Thread(new Runnable(){
				public void run() {
					synchronized(lock){
						System.out.println("step3");
						lock.notify();
					}
				}
			}).start();
			lock.wait();
			System.out.println("end");
		}
	}

}


代码质量比较水,还望轻拍。。。
分享到:
评论
2 楼 88355117 2010-10-13  
第一问输出为什么是start、step1、step2、end、step3能解释下吗?
1 楼 88355117 2010-10-13  
第一问输出为什么是start、step1、step2、end、step3能解释下吗?

相关推荐

Global site tag (gtag.js) - Google Analytics