”温故知新” なことなど

コメントは、タイトル下の"without comments"を押下して記入ください

Archive for the ‘マルチスレッド’ tag

マルチスレッド03

without comments

カウンターにコーヒーが並んでいるか確認するところ


class ShopMaster extends Thread{
	Counter counter;
	ShopMaster(Counter theCounter){
		this.counter = theCounter;
		}

マスターがコーヒーを作るところが処理される


	public void run(){
		while(true){
			try{
			counter.putCoffee();
			//コーヒーをぼちぼち作る
			Thread.sleep((int)(3000 * Math.random()));
			}catch(InterruptedException e){}
			}
		}
	}

作られたコーヒーが誰によって作られたか表示される


class CoffeeDrinker extends Thread {
	Counter counter;
	String name;
	CoffeeDrinker(Counter theCounter.String theName){
		this.counter = theCounter;
		this.name	 = theName;
	}

ここから作られたコーヒーを飲むところが始まる


	public void run(){
		while(true){
			try{
				counter.getCoffee(this.name);
				//コーヒーをボチボチ飲む
				Thread.sleep((int)(10000 * Math.random()));
				}catch(InterruptedException e){}
		}
	}
}

Written by nextschool

2月 22nd, 2009 at 5:53 pm

Posted in 情報,言語

Tagged with ,

マルチスレッド02

without comments


class Counter{
	Vector coffees;
	Countre(){
		coffees = new Vector();
	}

ここからスレッドを同期させるメソッドを指定する。


public synchronized void getCoffee(String name)
	throws InterruptedException{
	//だれか一人を起こす瞬間に、他のだれかがコーヒーを
	//持って行ってしまう可能性があるのでwhile
	while(coffee.size() == 0){
		System.out.println(name +"can NOT drink a COFFEE!");
		wait();
	}
	coffee.removeElementAt(0);
	System.out.println(name +"can drink & COFFEE!");
	System.out.println(coffees.toString());

	if(coffee.size() == 4) notifyAll();
}

で、ここからもスレッドの同期をさせる


	public synchronized void putCoffee()
		throws InterruptedException{

	coffees.addElement(new String("coffee"));
	if(coffee.size()>4){
		System.out.println("It's AKAJI!");
	wait();
	}
	System.out.println("Master made & COFFEE");
	System.out.println(coffee.toString());

	if(coffee.size() == 1)notify();
	}
}

Written by nextschool

2月 22nd, 2009 at 5:39 pm

Posted in 情報

Tagged with ,

マルチスレッドの練習

without comments


public class CoffeeShop {

	public static void main(String args[]){
		Counter counter new Counter();
		ShopMaster master = new ShopMaster(counter);
		CoffeeDrinker itota = new CoffeeDrinker(counter, "itota");
		CoffeeDrinker fukuta = new CoffeeDrinker(counter, "fukuta");
		CoffeeDrinker hatto = new CoffeeDrinker(counter, "hatto");
		master.start();
		itota.start();
		fukuta.start();
		hatto.start();
	}
}

Written by nextschool

2月 22nd, 2009 at 2:20 am

Posted in 情報

Tagged with ,