日期:2014-05-20  浏览次数:20682 次

Java Swing中的线程问题
/**
 * 
 */
package com.thread;

import java.util.Vector;

/**
 * @author Administrator
 *
 */

/***** 线程通信实现生产者/消费者模型 *******/
// 产品类
class Production {
int number;

// 构造方法
public Production(int number) {
this.number = number;
}
}

// 向量类
@SuppressWarnings( { "serial", "unchecked" })
class myVector extends Vector {
public static int inNumber;

// 构造方法
public myVector() {
super(1, 1);
}

// 向容器中添加元素
synchronized void putElement() {
// 向量里有10个对象,容器满
if (this.size() == 10) {
System.out.println("没有空间了,等待……");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
inNumber++;

Production production = new Production(inNumber);

// 向容器中添加产品
this.addElement(production);

System.out.println("生产产品:" + production.number);

notify();
}
}

// 从容器中移除产品
synchronized void getElement() {
// 向量空,容器空
if (this.isEmpty()) {
System.out.println("没有商品了,等待……");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

// 返回索引处的组件
Production production = (Production) elementAt(0);

System.out.println("包装产品:" + production.number);

// 移除容器中已包装好的产品
this.removeElementAt(0);

notify();
}
}

// 消费者
class Consume implements Runnable {
myVector vector;

// 构造方法
public Consume(myVector vector) {
this.vector = vector;

new Thread(this).start();
}

@Override
public void run() {
while (true) {
Double d = new Double(Math.random() * 1000);

try {
Thread.sleep(d.intValue());
} catch (InterruptedException e) {
e.printStackTrace();
}

// 获得产品
vector.getElement();
}
}
}

public class Product implements Runnable {

myVector vector;

public Product(myVector vector) {
this.vector = vector;

new Thread(this).start();
}

@Override
public void run() {

while (true) {
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}

// 向容器中添加商品
vector.putElement();
}

}

public static void main(String[] args) {

myVector myvector = new myVector();

new Product(myvector);
new Consume(myvector);

}

}

运行结果如下:
生产产品:1
包装产品:1
没有商品了,等待……
生产产品:2
包装产品:2
没有商品了,等待……
生产产品:3
包装产品:3
没有商品了,等待……
生产产品:4
包装产品:4
没有商品了,等待……
生产产品:5
包装产品:5
生产产品:6
包装产品:6
生产产品:7
包装产品:7
没有商品了,等待……
生产产品:8
包装产品:8
没有商品了,等待……
生产产品:9
包装产品:9
没有商品了,等待……
生产产品:10
包装产品:10
没有商品了,等待……
生产产品:11
包装产品:11
生产产品:12
包装产品:12
生产产品:13
包装产品:13
没有商品了,等待……
生产产品:14
包装产品:14
没有商品了,等待……
生产产品:15
包装产品:15
没有商品了,等待……
生产产品:16
包装产品:16
生产产品:17
包装产品:17
生产产品:18
生产产品:19
包装产品:18
生产产品:20
生产产品:21
生产产品:22
包装产品:19
生产产品:23
生产产品:24
包装产品:20
生产产品:25
生产产品:26
包装产品:21
包装产品:22
生产产品:27
生产产品:28
包装产品:23
生产产品:29
包装产品:24
生产产品:30
生产产品:31
包装产品:25
生产产品:32
生产产品:33
包装产品:26
包装产品:27
包装产品:28
包装产品:29
包装产品:30
生产产品:34
包装产品:31
包装产品:32
生产产品:35
包装产品:33
生产产品:36
生产产品:37
包装产品:34
包装产品:35