本文详细介绍线程基础(第二部分)Java线程的缺陷和副作用几解决办法
表A: 演示高级线程方法的伪代码
class ProdCons {
class List {
public synchronized boolean add(Object o)
{...}
public synchronized boleanremove (Object o)
{...}
}
List data = new List();
ProdThread producer = null;
ConsThread consumer = null;
ProdCons() {
producer = new ProdThread(this);
consumer = new ConsThread(this);
producer.start();
consumer.start();
}
}
消费者和生产者的类,请见表B和表C。
表B: Class ConsThread
class ConsThread extends Thread {
ProdCons parent;
ConsThread(ProdCons parent) {
this.parent = parent;
}
public synchronized void canConsume() {
notify();
}
public void run() {
boolean consumed;
do {
synchronized(this) {
try { wait();}
catch (Exception e) { ; }
}
do {
String str = (String)parent.list.remove();
if ( null == str) {
consumed = false;
break;
}
consumed = true;
System.out.println("Consumer
=>consumed " + str);
}
while ( true );
}
while (consumed);
}
}
表C: Class ProdThread
class ProdThread extends Thread {
ProdCons parent;
ProdThread(ProdCons parent) {
this.parent = parent;
}
public void run() {
for ( int i = 0; i < 10; i++) {
String str = new String("ImAString" + i);
System.out.println("Producer produced " + str);
parent.list.add(str);
parent.consumer.canConsume();
}
parent.consumer.canConsume();
}
}
责编:豆豆技术应用