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

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();
			}
		}
	}
}

你可能感兴趣的:(java)