多线程学习-----线程同步(四)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/havebeenstand/article/details/83474977

两个线程要执行的代码片段要实现同步互斥的效果,它们必须用同一个Lock对象,锁是上在代表要操作的资源类的内部方法中的,而不是在线程代码中,

问题:子线程循环10次,回到主线程执行100次,接着又回到子线程执行10次,再回到主线程执行100次,如此循环50次,该如何实现?

public class ThreadCommunicationStudy {
	
	
	public static void main(String[] args) {
		//线程代码
		Bussiness b = new Bussiness();
		new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i = 1;i<=50;i++){
					b.subThreadCreate(i);
				}
			}
		}).start();
		
		for(int i = 1;i<=50;i++){
			b.mainThreadCreate(i);
		}
		
	}
	
}
//资源类
class Bussiness{
	//指示是否该子线程执行的布尔临时变量
	private boolean isSub = true;
	
	//子线程资源方法
	public synchronized void subThreadCreate(int i){
		//如果不该子线程执行,子线程等待
		while(!isSub){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		for(int j = 1;j<=10;j++){
			System.out.println("sub thread number of "+j+" loop of "+i);
		}
		//子线程执行完,让指示是否该子线程执行为false
		isSub = false;
		//唤醒等待的主进程
		this.notify();
	}
	//主线程资源方法
	public synchronized void mainThreadCreate(int i){
		//如果该子进程去执行,让主进程等待
		while(isSub){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		for(int j = 1;j<=100;j++){
			System.out.println("MAIN thread number of "+j+" loop of "+i);
		}
		//主进程执行完,轮到子进程去执行,令isSub为true
		isSub = true;
		//唤醒等待的子进程
		this.notify();
	}
}

猜你喜欢

转载自blog.csdn.net/havebeenstand/article/details/83474977