线程间通信
Posted weixin_ancenhw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程间通信相关的知识,希望对你有一定的参考价值。
判断、干活、通知三步骤
this.wait()等待
this.notifyAll()通知其他线程
虚假唤醒if,因为是异步的,建议使用while避免异步唤醒操作
//定义票数
private int tickCount=0;
//线程++
public synchronized void tickeAdd() throws InterruptedException
while(tickCount!=0)
wait();
System.out.println("线程切换数据:"+tickCount);
tickCount++;
this.notifyAll();
//线程--
public synchronized void tickeReduce() throws InterruptedException
while(tickCount!=1)
wait();
System.out.println("线程切换数据:"+tickCount);
tickCount--;
this.notifyAll();
@Test
public void contextLoads()
RenrenApplicationTests renrenApplicationTests = new RenrenApplicationTests();
for (int i = 0; i < 20; i++)
new Thread(()->
try
renrenApplicationTests.tickeAdd();
catch (InterruptedException e)
e.printStackTrace();
try
renrenApplicationTests.tickeReduce();
catch (InterruptedException e)
e.printStackTrace();
).start();
//定义票数
private int tickCount = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
//线程++
public void tickeAdd() throws InterruptedException
lock.lock();
try
while (tickCount != 0)
condition.await();
System.out.println("线程切换数据:" + tickCount);
tickCount++;
condition.signalAll();
finally
lock.unlock();
//线程--
public void tickeReduce() throws InterruptedException
lock.lock();
try
while (tickCount != 1)
condition.await();
System.out.println("线程切换数据:" + tickCount);
tickCount--;
condition.signalAll();
finally
lock.unlock();
@Test
public void contextLoads()
RenrenApplicationTests renrenApplicationTests = new RenrenApplicationTests();
for (int i = 0; i < 20; i++)
new Thread(() ->
try
renrenApplicationTests.tickeAdd();
catch (InterruptedException e)
e.printStackTrace();
try
renrenApplicationTests.tickeReduce();
catch (InterruptedException e)
e.printStackTrace();
).start();
以上是关于线程间通信的主要内容,如果未能解决你的问题,请参考以下文章