表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
consumer
}
}
消費者和生產者的類
表B: Class ConsThread
class ConsThread extends Thread
{
ProdCons parent;
ConsThread(ProdCons parent)
{
this
}
public synchronized void canConsume()
{
notify();
}
public void run()
{
boolean consumed;
do
{
synchronized(this)
{
try { wait();
}
catch (Exception e) { ; }
}
do
{
String str = (String)parent
if ( null == str)
{
consumed = false;
break;
}
consumed = true;
System
}
while ( true );
}
while (consumed);
}
表C: Class ProdThread
class ProdThread extends Thread
{
ProdCons parent;
ProdThread(ProdCons parent)
{
this
}
public void run()
{
for ( int i =
{
String str = new String(
System
parent
parent
}
parent
}
}
注意
線程和Sun JDK
線程提供了一項很有價值的服務
如果我們回到上面的生產者/消費者例子
線程的第二個問題有關不一致的問題
處理這個不一致的問題的最簡單的方法就是派生一個新的線程類
表D: Class MyThread
public class MyThread extends Thread
{
//States the thread can be in
static final int STATE_RUNNING =
static final int STATE_STOP =
static final int STATE_SUSPEND =
private int currentState = STATE_RUNNING;
// The public method changeState allows
// another process to poke at that hread
// and tell it to do something when it
// next gets a chance
public final synchronized void
changeState(int newState)
{
currentState = newState;
if (STATE_RUNNING == currentState)
notify();
// Must have been suspended
}
private synchronized boolean currentState()
{
// If we where asked to suspend
// just hang out until we are
// asked to either run or stop
while ( STATE_SUSPEND == currentState)
{
try{ wait(); }
catch (Exception e) {};
}
if ( STATE_STOP == currentState )
return false;
else
return true;
}
public void run()
{
do
{
if (currentState() == false)
return; // Done
// Perform some work
}
while (true);
}
}
MyThread類的用戶可以重載run方法
結論
線程功能強大而使用復雜
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27773.html