Archive for the ‘マルチスレッド’ tag
マルチスレッド03
カウンターにコーヒーが並んでいるか確認するところ
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){}
}
}
}
マルチスレッド02
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();
}
}
マルチスレッドの練習
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();
}
}