java一对一生产者消费者多线程练习

来源:互联网 发布:java jdk官网下载 编辑:程序博客网 时间:2024/06/06 00:47

转载于:点击打开链接

消费者OTO_Consumer类:


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
 * Created by YouGuessWho on 2017/4/22.
 */
publicclass OTO_Consumer extendsThread {
    /**
     * 编号
     */
    privateInteger num;
    privateObject lock;
 
    publicOTO_Consumer(String name,Integer num,Object lock){
        super();
        this.setName(name);
        this.setNum(num);
        this.setLock(lock);
    }
 
    publicvoid run(){
        try{
            while(true) {
                this.consume();
                this.sleep(3000);
            }
        }catch(finalException ex){
            System.out.println(ex);
        }
    }
 
    privatevoid consume()throwsException{
        synchronized(this.lock){
            if(Warehouse.simpleWH==null){
                this.say("没货了");
                lock.wait();
            }
            this.say("消费了"+Warehouse.simpleWH);
            Warehouse.simpleWH = null;
            lock.notify();
        }
    }
 
    privatevoid say(String word){
        System.out.println(String.format("时间:%s,%s,编号%03d:%s",System.currentTimeMillis(),this.getName(),this.getNum(),word));
    }
 
    publicInteger getNum() {
        returnnum;
    }
 
    publicvoid setNum(Integer num) {
        this.num = num;
    }
 
    publicObject getLock() {
        returnlock;
    }
 
    publicvoid setLock(Object lock) {
        this.lock = lock;
    }
}


生产者():


0 0
原创粉丝点击