Java jdk1.5新的多线程写法:20150602
/*
Lock接口的例子
注意事项:
1 定义lock接口
2 定义每个代码块的自己的锁
3 while循环里面让线程等待
4try{3}finally{释放锁}、
5 必须抛出异常
*/
实现代码:
import java.util.concurrent.locks.*;
class pcDemo
{
publicstatic void main(String[] args)
{
Resr = new Res();
Propro = new Pro(r);
Conncon = new Conn(r);
Threadt1 = new Thread(pro);
Threadt2 = new Thread(pro);
Threadt3 = new Thread(con);
Threadt4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Res
{
privateString name;
privateint count = 1;
privateboolean pFlag = false;//标记
privateLock lock = new ReentrantLock();//定义锁接口
privateCondition condition_con = lock.newCondition();//定义消费的锁
privateCondition condition_pro = lock.newCondition();//定义生产锁
public void set(String name)throwsInterruptedException
{
//生产产品
lock.lock();//加锁
try
{
while(pFlag)
{
condition_pro.await();
}
this.name= name + "......" + count++;
System.out.println(Thread.currentThread().getName()+ "..." + "生产者" +this.name );
pFlag= true;
condition_con.signal();
}
finally
{
lock.unlock();
}
}
public void out()throws InterruptedException
{
lock.lock();
try
{
while(!pFlag)
{
condition_con.await();
}
System.out.println(Thread.currentThread().getName()+ ".........." + "消费了" +this.name );
pFlag= false;
condition_pro.signal();
}
finally
{
lock.unlock();
}
}
}
class Pro implements Runnable
{
privateRes r;
Pro(Resr)
{
this.r= r;
}
publicvoid run()
{
intx = 100;
while(--x> 0)
{
try
{
r.set("+冰激凌+");
}
catch(InterruptedExceptione)
{}
}
}
}
class Conn implements Runnable
{
privateRes res;
Conn(Resres)
{
this.res= res;
}
publicvoid run()
{
while(true)
{
intx = 100;
while(--x> 0)
{
try
{
res.out();
}
catch(InterruptedExceptione)
{}
}
}
}
}