您的位置:首页 > 其它

子线程循环10次,紧接着主线程循环100次,来回50次

2015-05-11 16:55 274 查看
package cn.test.thread;

/*
 * 子线程10次,主线程100次,来回50次
 */
public class ThreadTest1 {

	public static void main(String[] args) throws InterruptedException {
		ThreadTest1 tt = new ThreadTest1();
		tt.init();
	}
	
	public void init() throws InterruptedException {
		final Business bussiness = new Business();
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 50; i++) {
					bussiness.subThread();
				}
			}
		}).start();
		Thread.sleep(1000);  //此行为了让主线程让出CPU,让子线程先执行
		for (int i = 0; i < 50; i++) {
			bussiness.mainThread();
		}
	}
	
	class Business {
		public synchronized void mainThread() {
			for (int i = 0; i < 100; i++) {
				System.out.println(Thread.currentThread().getName()+" execute"+i);
			}
			this.notify();
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		public synchronized void subThread() {
			for (int i = 0; i < 10; i++) {
				System.out.println(Thread.currentThread().getName()+" execute"+i);
			}
			this.notify();
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐