Java notify wait

wait 和 notify 是Object类而非Thread类的两个方法,只有在线程同步的时候才有效,只出现在synchronize方法或块中。

wait(0)  无限等待

notify()

import java.util.*;


public class JwaitTest {

	static List<String> pic = new ArrayList<String>();
	
	static boolean done = false;
	
	static class Download extends Thread{

		private String[] image = {"kobe.jpg","tmac.jpg"};
		@Override
		public void run() {
			for(int i=0;i<image.length;i++){
				int time = new Random().nextInt(100)*10;
				System.out.println("下载图片:"+time);
				try {
					Thread.sleep(time);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				synchronized(pic){
					System.out.println("Download" + image[i]);
					pic.add(image[i]);
					pic.notify();
				}
			}
			done = true;
			System.out.println("Download thread exit!");
		}
		
	}
	
	static class Display extends Thread{

		@Override
		public void run() {
			while(!done){
				synchronized(pic){
					try {
						pic.wait(200);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					if(pic.size()>0){
						System.out.println("Display\t"+pic.remove(0));
					}
				}
			}
			System.out.println("Display thread exit!");
		}
		
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Download().start();
		new Display().start();

	}

}

public class JwaitTest {

	static List<String> pic = new ArrayList<String>();
	
	static boolean done = false;
	
	static class Download extends Thread{

		private String[] image = {"kobe.jpg","tmac.jpg"};
		@Override
		public void run() {
			for(int i=0;i<image.length;i++){
				int time = new Random().nextInt(100)*10;
				System.out.println("下载图片:"+time);
				try {
					Thread.sleep(time);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				synchronized(pic){
					System.out.println("Download" + image[i]);
					pic.add(image[i]);
					pic.notify();
				}
			}
			done = true;
			System.out.println("Download thread exit!");
		}
		
	}
	
	static class Display extends Thread{

		@Override
		public void run() {
			while(!done){
				synchronized(pic){
					try {
						pic.wait(200);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					if(pic.size()>0){
						System.out.println("Display\t"+pic.remove(0));
					}
				}
			}
			System.out.println("Display thread exit!");
		}
		
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Download().start();
		new Display().start();

	}

} 

  多个线程挑选一个

notifyAll()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值