java线程面试题之--两个线程,子线程10次,主线程5次,子线程10次,主线程5次,如此往复50次

package com.thread;

//两个线程,子线程10次,主线程5次,子线程10次,主线程5次,如此往复50次

//首先实现互斥,然后实现通信
public class TranditionalThreadCommunication {

	final Business business = new Business();

	public static void main(String[] args) {
		new TranditionalThreadCommunication().init();
	}

	private void init() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				for(int i=0;i<50;i++)
				{
				  business.main();
				}
			}
		}).start();

		for(int i=0;i<50;i++)
		{
			business.sub();
		}
	}

	class Business {
		private Boolean isShouldSub = true;

		public synchronized void main() {
			if (!isShouldSub) {
				for (int i = 0; i < 5; i++) {
					System.out.println("主线程第" + i + "次");
				}
				isShouldSub = true;
				this.notify();
			} else {
				try {
					this.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		public synchronized void sub() {
			if (isShouldSub) {
				for (int j = 0; j < 10; j++) {
					System.out.println("子线程第" + j + "次");
				}
				isShouldSub = false;
				this.notify();
			} else {
				try {
					this.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

相关内容推荐