1. 程式人生 > >JAVA#多執行緒練習'札記

JAVA#多執行緒練習'札記

 public static void main(String[] args) {
        Clerk clerk=new Clerk();
        Customer c1=new Customer(clerk);
        Productor p1=new Productor(clerk);
        Thread t1=new Thread(c1);
        Thread t2=new Thread(p1);
        Thread t3=new Thread(p1);
        t1.setName("kobeSong");
        t2.setName("SongAI");
        t3.setName("Iverson");
        t2.start();
        t3.start();
        t1.start();
    }
}
class Customer implements Runnable {
    Clerk clerk;
    public Customer(Clerk clerk) {
        this.clerk = clerk;
    }
    @Override
    public void run() {
        while (true) {
            clerk.minus();
        }
    }
}
class Productor implements Runnable{
    Clerk clerk;
    public Productor(Clerk clerk){
        this.clerk=clerk;
    }
    @Override
    public  void run() {
        while (true){
            clerk.add();
        }
    }
}
class Clerk{
    int NumProduct;
    public synchronized void add() {
        if (NumProduct >= 24 ) {
            try {
                wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }else{
            NumProduct++;
            System.out.println(Thread.currentThread().getName()+"produce"+NumProduct+"th shots");
            notifyAll();

        }
    }
    public synchronized void minus() {
        if (NumProduct > 0) {
            NumProduct--;
            System.out.println(Thread.currentThread().getName()+"consume"+NumProduct+"th shots");
            notifyAll();
        }else{
            try {
                wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}