Java notify wait

3535 ワード

waitとnotifyはThreadクラスではなくObjectクラスの2つのメソッドであり、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();

	}

} 

複数のスレッドから1つを選択
notifyAll()