package com.dq;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadTest
{
private static ReentrantLock lock = new ReentrantLock();
private static Condition condition = lock.newCondition();
public static class T1 extends Thread
{
@Override
public void run()
{
System.out.println("线程" + this.getName() + "准备去获得锁");
lock.lock();
System.out.println("线程" + this.getName() + "得到了锁");
System.out.println("线程" + this.getName() + "开始做事-------------------------");
for(int index = 0; index < 20; index++)
{
System.out.println("线程" + this.getName() + ":" + index);
if(index == 10)
{
try
{
condition.await();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
lock.unlock();
System.out.println("线程" + this.getName() + "结束做事-------------------------");
}
}
public static class T2 extends Thread
{
@Override
public void run()
{
System.out.println("线程" + this.getName() + "准备去获得锁");
lock.lock();
System.out.println("线程" + this.getName() + "得到了锁");
System.out.println("线程" + this.getName() + "开始做事-------------------------");
for(int index = 0; index < 20; index++)
{
System.out.println("线程" + this.getName() + ":" + index);
if(index == 10)
{
condition.signal();
}
}
lock.unlock();
System.out.println("线程" + this.getName() + "结束做事-------------------------");
}
}
public static void main(String[] args) throws Exception
{
T1 t1 = new T1();
t1.setName("线程1");
T2 t2 = new T2();
t2.setName("线程2");
t1.start();
t2.start();
t1.join();
t2.join();
}
}
利用Condition实现线程通信
最新推荐文章于 2024-06-30 14:52:34 发布