线程间同步控制

子线程循环10次,接着主线程循环10,接着又回到子线程循环10次,接着再回到主线程又循环10,如此循环5次

public class ThreadTest{
	public boolean first = true;//空值顺序, important
	
	public synchronized void subTask() throws InterruptedException{
		for(int i=0; i<5; i++){
			if(!first)
				this.wait();
			for(int j=0; j<10; j++){
				System.out.println("SSSSSSSSSSSSSSSSSSSSSSSSSSSSS j = "+j);
			}
			first = false;
			this.notify();
//			Thread.sleep(2000);
		}
	}
	
	public synchronized void mianTask() throws InterruptedException{
		System.out.println("mainTask");
		for(int i=0; i<5; i++){
			if(first){
				this.wait();
			}
			for(int j=0; j<10; j++){
				System.out.println("mmmmmmmmmmmmmmmmmmmmmmmmmmmmm j = "+j);
			}
			first = true;
			this.notify();
				
		}
	}
	
	public static void main(String [] args) throws InterruptedException{
		final ThreadTest test = new ThreadTest();
		new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					test.subTask();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}).start();
		
		test.mianTask();
	}

	

}

notify()告诉等待当前锁的线程, 你们可能得到一个锁资源, 但是只有在执行wait()释放当前锁资源之后, 其他等待当前锁的线程才会获得锁并且执行。


下面程序说明了, 只有在调用一次notify(), 然后再调用一次wait()之后, 才会唤醒mainTask, 不论中间执行了多少操作, 或者等待了多长时间。

public class ThreadTest{
	public boolean first = true;//空值顺序, important
	public synchronized void subTask() throws InterruptedException{
		for(int i=0; i<5; i++){
			System.out.println("i = "+i);
			if(!first&&i%2==0){
				System.out.println("wait()");
				this.wait();
			}
			for(int j=0; j<10; j++){
				System.out.println("SSSSSSSSSSSSSSSSSSSSSSSSSSSSS j = "+j);
			}
			first = false;
			if(i%2==0){
				System.out.println("notify()");
				this.notify();
			}
//			Thread.sleep(2000);
		}
	}
	
	public synchronized void mianTask() throws InterruptedException{
		System.out.println("mainTask");
		for(int i=0; i<5; i++){
			if(first){
				this.wait();
			}
			for(int j=0; j<10; j++){
				System.out.println("mmmmmmmmmmmmmmmmmmmmmmmmmmmmm j = "+j);
			}
			first = true;
			this.notify();
				
		}
	}
	
	public static void main(String [] args) throws InterruptedException{
		final ThreadTest test = new ThreadTest();
		new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					test.subTask();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}).start();
		
		test.mianTask();
	}

	

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WitsMakeMen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值