`

Java notify wait

    博客分类:
  • JAVA
 
阅读更多

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()

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics