您的位置:首页 > 编程语言 > Java开发

java线程模拟生产者与消费者

2009-04-12 13:57 489 查看
public class ProducerConsumer
{
public static void main( String[] args )
{
SyncStack sync = new SyncStack() ;
Producer pro = new Producer( sync ) ;
Consumer con = new Consumer( sync ) ;

for( int i =  0 ; i < 1 ; i ++ )
{
new Thread( pro , String.valueOf( i ) ).start() ;
new Thread( con , String.valueOf( i )).start() ;
}
}
}

/**
* 窝头堆栈
* */
class SyncStack
{
private Woto[] wos = new Woto[600] ;
private int index ;

public synchronized void push( Woto woto )
{
while( wos.length == index )
{
try
{
this.wait() ;
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
}

this.notify() ;

wos[ index ] = woto ;
++ index ;
System.out.println( Thread.currentThread().getName() + "_____________生产了馒头->>" + woto ) ;
}

public synchronized Woto pop()
{
while( 0 == index )
{
try
{
this.wait() ;
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
}

this.notify() ;
-- index ;
System.out.println( Thread.currentThread().getName() + "%%%消费了馒头->>" + wos[index] ) ;
return wos[ index ] ;

}
}

/**
* 窝头类
* */
class Woto
{
private String name ;

public Woto( String name )
{
this.name = name ;
}

public String toString()
{
return "[窝头:" + this.name + "]" ;
}
}

/**
* 生产者
* */
class Producer implements Runnable
{
private SyncStack wotos ;

public Producer( SyncStack wotos )
{
this.wotos = wotos ;
}

public void run()
{
for( int i = 0 ; i < 2000  ; i ++ )
{
Woto woto = new Woto( String.valueOf( i ) ) ;
this.wotos.push( woto ) ;

//			try
//			{
//				Thread.sleep( (int)(Math.random() * 2) ) ;
//			}
//			catch ( InterruptedException e )
//			{
//				e.printStackTrace();
//			}
}
}
}

/**
* 消费者
* */
class Consumer implements Runnable
{
private SyncStack wotos ;

public Consumer( SyncStack wotos )
{
this.wotos = wotos ;
}

public void run()
{
for( int i = 0 ; i < 2000  ; i ++ )
{
this.wotos.pop() ;

try
{
Thread.sleep( (int)(Math.random() * 2 ) ) ;
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: