JAvaマルチスレッド問題


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

public class Store {
	
	private List<Integer> st = new ArrayList<Integer>();
	
	public synchronized void add(int i){
		if (st.size() == 4) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}else{
			st.add(i);
			System.out.println("size : " + st.size());
			this.notifyAll();
		}
	}
	
	public  synchronized int get(){
		if (st.size() == 0) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} 
		int i = st.remove(st.size()-1);
		this.notifyAll();
		return i;
	}
}
public class Producer implements Runnable{
	private Store s ;
	
	Producer(Store s){
		this.s = s;
	}
	public void produce(){
		System.out.println("produce......");
		for (int i = 0; i < 20; i++) {
			s.add(i);
			System.out.println("produce : " + i);
			try {
				Thread.sleep((long) (Math.random()*1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void run() {
		produce();
	}
}

public class Customer implements Runnable{
	
	private Store s ;
	
	Customer(Store s){
		this.s = s;
	}
	public void custom(){
		System.out.println("custom.......");
		for (int i = 0; i < 20; i++) {
			System.out.println("customing : " + s.get());
			try {
				Thread.sleep((long) (Math.random()*1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	public void run() {
		custom();
	}

}
public class Test {
	
	public static void main(String[] args) {
		Store s = new Store();
		Customer c = new Customer(s);
		Producer p = new Producer(s);
		
		
		new Thread(p).start();
		new Thread(c).start();
		
	}

}

------------------------
public class Test implements Runnable{
	
	private static int sum = 10;
		
	private boolean flag = true;

	public synchronized  void aaaa(){
		if (flag) {
			sum--;
			System.out.println(Thread.currentThread().getName() + "--->" + sum);

		}
	}
	public void run() {
		while (true) {
			if (sum > 0) {
				aaaa();
			}else{
				System.out.println(Thread.currentThread().getName() + "--->over!");
				break;
			}
		}
		
	}
	public static void main(String[] args) {
		Test t = new Test();
		for (int i = 0; i < 2; i++) {
			new Thread(t,"thread no : " + i).start();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}