线程同步、通信

<span style="font-size: 18px; font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">线程同步,当两个线程同时访问一个对象时,出现同步问题。使用关键字:synchronized</span><span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"> </span><span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px; background-color: rgb(255, 255, 255);">解决同步有两种:1、 同步方法2、同步代码</span>
</pre><pre name="code" class="java">
<pre name="code" class="html"><span style="font-size:18px;">synchronized(t){
			for(int i=0;i<10;i++){
				t.a = t.a +i;
				System.out.println(this.getName()+"a======"+t.a);
				try {
					Thread.sleep(1);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}</span>


 

线程通信,多个线程同时访问一个对象时,存在同步,这时,就存在线程通信,当一个线程在执行时,另一个线程处在等待的过程中,当这个线程执行完成后,就会通知另一个线程去执行。典型的模型就是“生产消费模型”。简单地说:此模型的规则就是,一个放东西,一个拿东西,只有当放好了的时候才能拿。具体解释是:生产和消费线程共同操作一个集合,生产线程放入对象,消费线程取出对象!仅当集合中没有对象时,生产线程会放入一个对象,如有集合中有一个对象时,消费线程要马上取出这个对象。

public void run() {
		super.run();
		synchronized (ProductThread.list) {
			while (true) {
				// 判断仓库是否还有手机
				if (ProductThread.list.size() == 0) {
					try {
						<strong style="background-color: rgb(51, 255, 255);">ProductThread.list.wait();</strong>
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				// 从队列中移出一个手机
				MiPhone mp = ProductThread.list.remove(0);

				System.out.println("销售人员卖出了一个手机,手机型号为:" + mp.getName());

				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// 提醒生产者,手机买完了,你必须继续生产
				<span style="color:#ff6666;"><strong style="background-color: rgb(102, 255, 255);">ProductThread.list.notify();</strong></span>
			}



super.run();
		synchronized(list){
			//不停执行,生产手机
			while(true){
				if(list.size()>10){
					try {
						<strong style="background-color: rgb(51, 255, 255);">list.wait();</strong>
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				MiPhone mp = new MiPhone();
				mp.setName("小米"+count);
				count++;
				//把生产出来的手机添加到仓库list中
				list.add(mp);
				System.out.println("生产商,生产了一个小米手机,手机型号是:"+mp.getName());
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				<strong style="background-color: rgb(51, 255, 255);">//提醒消费者,手机已经生产完成,可以进行销售
			    list.notify();</strong>
			}
     需要注意的是1、 wait和notify必须在同步锁之内使用
                           2、同步锁锁定对象和wait、notify对象必须同一个
                           3、当对象wait挂起状态时候是会释放同步锁的


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值