黑马程序员技术交流社区
标题:
分享下-多线程实现数组的同步赋值和同步打印
[打印本页]
作者:
王自强
时间:
2012-8-29 16:02
标题:
分享下-多线程实现数组的同步赋值和同步打印
import java.util.concurrent.locks.*;
class BoundedBuffer
{
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final Object[] items = new Object[100];
int count,putptr,takeptr;
public void put(Object x)throws InterruptedException
{
lock.lock();
try
{
while(count==items.length)
notFull.await();
items[putptr] = x;
System.out.println(Thread.currentThread().getName()+"在向数组中添加第"+putptr+"号角标的元素:"+x);
if(++putptr == items.length)
putptr = 0;
++count;
notEmpty.signal();
}
finally
{
lock.unlock();
}
}
public Object take()throws InterruptedException
{
lock.lock();
try
{
while(count==0)
notEmpty.await();
Object x = items[takeptr];
System.out.println(Thread.currentThread().getName()+"在从数组中取出第"+takeptr+"号角标的元素:"+x);
if(++takeptr == items.length)
takeptr = 0;
--count;
notFull.signal();
return x;
}
finally
{
lock.unlock();
}
}
}
class Put implements Runnable
{
BoundedBuffer bb;
int x = 20;
Put(BoundedBuffer bb)
{
this.bb = bb;
}
public void run()//不能抛,只能在内部进行try
{
while(x-->0)
{
try
{
bb.put(x);
}
catch (InterruptedException e)
{
}
}
}
}
class Take implements Runnable
{
BoundedBuffer bb;
int x = 20;
Take(BoundedBuffer bb)
{
this.bb = bb;
}
public void run()//不能抛,只能在内部进行try
{
while(x-->0)
{
try
{
System.out.println(bb.take());
}
catch (InterruptedException e)
{
}
}
}
}
class demo
{
public static void main(String[] s)
{
BoundedBuffer bb = new BoundedBuffer();
Put p = new Put(bb);
Take t = new Take(bb);
new Thread(p).start();
new Thread(p).start();
new Thread(p).start();
new Thread(p).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2