多线程协作

线程1负责将初始值每次加1,直到100,在每次累加过程中,如果结果是10的倍数,通知线程2打印。

class M {
	private int num = 1;
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}

}

class CalThread implements Runnable {
	private M m;
	public CalThread(M m) {
		this.m = m;
	}

	@Override
	public void run() {
		synchronized (m) {
			while (m.getNum() < 100) {
			int t = m.getNum() + 1;
			m.setNum(t);
			if (t % 10 == 0) {
				m.notifyAll();
				try {
					m.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}
		}
		
	}

}

class PrintThread implements Runnable {
	private M m;

	public PrintThread(M m) {
		this.m = m;
	}

	@Override
	public void run() {
		synchronized (m) {
			try {
				while (!Thread.interrupted()) {
//					m.wait();
					System.out.println(m.getNum());
					m.notifyAll();
					if(m.getNum()==100)
						return;
					m.wait();
				}

			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
	}

}

class MyThread {
	public static void main(String[] args) {
		M m = new M();
		Thread t1 = new Thread(new CalThread(m));
		Thread t2 = new Thread(new PrintThread(m));
		t1.start();
		t2.start();
	}
}

输出结果:

10
20
30
40
50
60
70
80
90

100

(1)虽然线程的执行具有不确定性,但程序执行依然是按顺序执行,如果取消了打印线程中的注释,打印线程就会一直处于挂起状态;

(2)开始运行时,程序一直抛出java.lang.IllegalMonitorStateException 异常,原因是没按规则使用wait,notify,notifyAll等方法。

=================================================================
void notify() 
          唤醒在此对象监视器上等待的单个线程。 
 void notifyAll() 
          唤醒在此对象监视器上等待的所有线程。 
 void wait() 
          导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。
根据jdk的void notifyAll()的描述,“解除那些在该对象上调用wait()方法的线程的阻塞状态。该方法只能在同步方法或同步块内部调用。如果当前线程不是对象所得持有者,该方法抛出一个 java.lang.IllegalMonitorStateException 异常”
参考:http://blog.csdn.net/intlgj/article/details/6245226


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值