线程之间的通信

使用wait/notify方法实现线程间通信。这两个方法都是object类的方法,也就是说java为所有的对象都提供了中两个方法

1.wait和notify必须配合synchronized关键字使用

2.wait方法释放锁,notify方法不释放锁

wait方法有三种形式

1.无时间参数的wait(一直等待,直到其它线程通知)

2.带毫秒、毫微妙参数的wait(),这两种方法都是等待指定时间后自动苏醒

notify():唤醒在此同步监视器上等待的单个线程。如果所有线程都在此同步监视器上等待,则会唤醒其中一个线程。选择是任意性的。只有当前线程放弃对该同步监视器的锁定后(使用wait()方法),才可以执行被唤醒的线程。

notifyAll():唤醒在此同步监视器上等待的所有线程。只有当前线程放弃对该同步监视器的锁定后,才可以执行唤醒的线程。

实例1:

package com.aruisi.innofarm;
import java.util.ArrayList;
import java.util.List;

public class AddList {
	private volatile static List<Object> list = new ArrayList<>();
	public void add(){
		list.add("zzzz");
	}
	public int size(){
		return list.size();
	}
	public static void main(String[] args) throws InterruptedException {
		final AddList addList = new AddList();
		final Object lock = new Object();//对象锁
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					synchronized (lock) {
						System.out.println("t1启动..");
						for(int i = 0; i <10; i++){
							addList.add();
							System.out.println(Thread.currentThread().getName() + "----新添加了一个元素..");
							Thread.sleep(500);
							if(addList.size() == 5){
								System.out.println("已经向t2线程发出通知..");
								lock.notify();
							}
						}						
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}, "t1线程");
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (lock) {
					System.out.println("t2启动..");
					if(addList.size() != 5){
						try {
							lock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.println(Thread.currentThread().getName() + "收到通知,线程停止..");
					throw new RuntimeException();
				}
			}
		}, "t2线程");	
		t2.start();
		t1.start();
	}
}

运行结果:


在实际开发中,我们想让t2线程收到通知时,就立即停止,而不是让t1线程执行完后,t2再停止。修改代码

package com.aruisi.innofarm;

import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("all")
public class ListAdd1 {

	private volatile static List list = new ArrayList();	
	
	public void add(){
		list.add("bjsxt");
	}
	public int size(){
		return list.size();
	}
	
	public static void main(String[] args) {
		
		final ListAdd1 list1 = new ListAdd1();
		
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					System.out.println("进入t1线程。。。");
					for(int i = 0; i <10; i++){
						list1.add();
						System.out.println(Thread.currentThread().getName() + "----新添加了一个元素..");
						Thread.sleep(500);
					}	
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "t1线程");
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("进入t2线程。。。");
				while(true){
					if(list1.size() == 5){
						System.out.println(Thread.currentThread().getName() + " list size = 5 线程停止..");
						throw new RuntimeException();
					}
				}
			}
		}, "t2线程");		
		t1.start();
		t2.start();
	}
	
	
}
运行结果:


实现了预期效果。

还可以使用CountDownLatch对象的方法来实现

package com.aruisi.innofarm;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/**
 * @author zmk
 *
 */
@SuppressWarnings("all")
public class ListAdd2 {
	private volatile static List list = new ArrayList();	
	
	public void add(){
		list.add("zzzz");
	}
	public int size(){
		return list.size();
	}
	
	public static void main(String[] args) {
		
		final ListAdd2 list2 = new ListAdd2();
		final CountDownLatch countDownLatch = new CountDownLatch(1);
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
						System.out.println("t1启动..");
						for(int i = 0; i <10; i++){
							list2.add();
							System.out.println(Thread.currentThread().getName() + "----新添加了一个元素..");
							Thread.sleep(500);
							if(list2.size() == 5){
								System.out.println("已经向t2线程发出通知..");
								countDownLatch.countDown();
							}
						}						
					
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "t1线程");
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				
					System.out.println("t2启动..");
					if(list2.size() != 5){
						try {
							countDownLatch.await();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.println(Thread.currentThread().getName() + "收到通知,线程停止..");
					throw new RuntimeException();
				
			}
		}, "t2线程");	
		t2.start();
		t1.start();
	}
	
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值