マルチスレッド同期の問題の処理


public class BusinessFor {
	private boolean bShouldSub = true;

	public synchronized void sub(int j) {
		// , 
		while (!bShouldSub) { 
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		for (int i = 1; i <= 10; i++) {
			System.out.println("sub: " + i + ",loop: " + j);
		}
		
		bShouldSub = false;
		this.notify();// 
	}

	public synchronized void zhu(int j) {
		while (bShouldSub) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		for (int i = 1; i <= 100; i++) {
			System.out.println("main: " + i + ",loop: " + j);
		}
		
		bShouldSub = true;
		this.notify();// 
	}

}

これはマルチスレッド設計の考え方であり,スレッド同期の情報をsyn同期可能なクラスに置く.
スレッドテストの開始
public class ThreadTongBu {
	
	public static void main(String[] args) {
		final BusinessFor businessFor = new BusinessFor();
		
		new Thread(new Runnable() {
			public void run() {
				for(int i=1;i<=50;i++){
					businessFor.sub(i);
				}
			}
		}).start();
		
		for(int i=1;i<=50;i++){
			businessFor.zhu(i);
		}
		
	}
	
}