复习多线程,一个经典的实例:生产者消费者问题:
1.number表示产品编号,flag表示现在应该由谁来操作.
2.ProcuctData类中有两个同步方法setNumber()和getNumber(),分别代表生产者生产产品和消费者消费 产品。
3.两个线程类Producer和Consumer分别代表生产者与消费者
Java代码
- package cn.luxsoft.javafirststep.Thread;
-
- class ProductData {
-
-
- private int number;
-
-
- private boolean flag = true;
-
- public synchronized void setNumber(int number) {
- if (!flag) {
- try {
-
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- this.number = number;
-
-
- flag = false;
-
-
- notify();
- }
-
- public synchronized int getNumber() {
- if (flag) {
- try {
-
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
-
- flag = true;
-
-
- notify();
- return this.number;
- }
- }
-
- class Procucer extends Thread {
- private ProductData s;
-
- Procucer(ProductData s) {
- this.s = s;
- }
-
- @Override
- public void run() {
- for (int i = 0; i < 10; i++) {
- s.setNumber(i);
- System.out.println("P[" + i + "]生产.");
- }
- }
- }
-
- class Consumer extends Thread {
- private ProductData s;
-
- Consumer(ProductData s) {
- this.s = s;
- }
-
- public void run() {
- int i;
-
- do {
- i = s.getNumber();
- System.out.println("P[" + i + "]消费.**");
- } while (i != 9);
- }
- }
-
- public class ProducerConsumer {
-
-
-
-
-
- public static void main(String[] args) {
-
- ProductData s = new ProductData();
- Thread producer = new Procucer(s);
- Thread consumer = new Consumer(s);
-
- producer.start();
- consumer.start();
- }
-
- }
文章来源:
http://www.my1984.net/?action=show&id=177 MSN:
posted on 2009-03-08 17:12
kylixlu 阅读(784)
评论(0) 编辑 收藏 所属分类:
J2SE