多线程略难,时间也少. 第十二天,两天了还没吃透.
不过我想,多线程应该是java中的重点,学好这里下面才会相对轻松些...
很期待13天的String ~
- /*
- 生产者消费者练习
- synchronized版
- */
- public class ProducerConsumerDemo {
- public static void main(String[] args) {
-
- Resource res = new Resource();
-
- new Thread(new Producer(res)).start();
- new Thread(new Producer(res)).start();
- new Thread(new Consumer(res)).start();
- new Thread(new Consumer(res)).start();
- }
- }
- class Resource {
-
- private String name;
- private int count = 1;
- private boolean flag;
- public synchronized void set(String name) {
-
- while(flag)
- try{wait();} catch(Exception e) {}
- this.name = name + "--" + count++;
- System.out.println(Thread.currentThread().getName() + "\t生产者" + this.name);
- flag = true;
- notifyAll();
- }
-
- public synchronized void out() {
-
- while(!flag)
- try{wait();} catch(Exception e) {}
- System.out.println(Thread.currentThread().getName() + "\t\t消费者" + this.name);
- flag = false;
- notifyAll();
- }
- }
- class Producer implements Runnable {
- Resource res;
-
- public Producer(Resource res) {
-
- this.res = res;
- }
-
- public void run() {
-
- while(true) {
-
- res.set("商品");
- }
- }
- }
- class Consumer implements Runnable {
- Resource res;
-
- public Consumer(Resource res) {
-
- this.res = res;
- }
-
- public void run() {
-
- while(true) {
-
- try{Thread.sleep(500);} catch(Exception e) {}
- res.out();
- }
- }
- }
复制代码
|
|