子线程和 主线程 互换

package demo;

/**
 * 子线程循环5次,主线程循环10次。依次交替。整个交替循环3次
 *
 */
public class ThreadTest {
	public static void main(String[] args) {
		init();
	}
	
	static void init(){
		final Print p = new Print();//封装了 循环的动作
		new Thread(new Runnable(){

			@Override
			public void run() {
				for(int i=0;i<3;i++){
						p.subPrint(5);//循环5次
					}
				}
		}).start();
		
		new Thread(new Runnable(){
			
			@Override
			public void run() {
				for(int i=0;i<3;i++){
					p.mainPrint(10);//循环10次
				}
			}
			
		}).start();
	}

}

  

Print:

package demo;

/**
 * 两个方法之间互斥 (方法里面完整执行完),用 Sflag实现 开关控制 两个方法的切换
 *
 */
public class Print {
	boolean Sflag = true;
	public synchronized void subPrint(int num){
		while(!Sflag){//避免 伪唤醒
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for(int i=1;i<=num;i++){
			System.out.println(Thread.currentThread().getName()+":"+i);
		}
		Sflag = false;
		this.notifyAll();
	}
	public synchronized void mainPrint(int num){
		while(Sflag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for(int i=1;i<=num;i++){
			System.out.println(Thread.currentThread().getName()+":"+i);
		}
		Sflag = true;
		this.notifyAll();
	}

}

  

原文地址:https://www.cnblogs.com/GotoJava/p/7076737.html