码迷,mamicode.com
首页 > 编程语言 > 详细

线程通信问题

时间:2019-12-27 09:30:55      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:tran   唤醒   get   stat   ons   throw   现在   new t   static   

/**
* 现在两个线程,可以操作初始值为零的一个变量,实现一个线程对该变量加1,一个线程对该变量减1,交替,来10轮。
* 1 多线程编程工程化模板-上
* 1.1 线程 操作 资源类
* 1.2 高内聚 低耦合
*
* 2 多线程编程工程化模板-下
* 2.1 判断
* 2.2 干活
* 2.3 通知
*
* 3 多线程中的判断问题,也即不要避免:虚假唤醒
* 用while
*/

class ShareData {

private int number = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();

public void increment()throws Exception
{
lock.lock();
try
{
//1 判断
while(number != 0)
{
condition.await();//this.wait(); //A C
}
//2 干活
++number;
System.out.println(Thread.currentThread().getName()+"\t"+number);
//3 通知
condition.signalAll();//this.notifyAll();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}

public void decrement()throws Exception
{
lock.lock();
try
{
//1 判断
while(number == 0)
{
condition.await();//this.wait(); //A C
}
//2 干活
--number;
System.out.println(Thread.currentThread().getName()+"\t"+number);
//3 通知
condition.signalAll();//this.notifyAll();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}


/* public synchronized void increment()throws Exception
{
//1 判断
while(number != 0)
{
this.wait(); //A C
}
//2 干活
++number;
System.out.println(Thread.currentThread().getName()+"\t"+number);
//3 通知
this.notifyAll();

}

public synchronized void decrement()throws Exception
{
//1 判断
while(number == 0)
{
this.wait();
}
//2 干活
--number;
System.out.println(Thread.currentThread().getName()+"\t"+number);
//3 通知
this.notifyAll();
}*/
}


public class ProdConsumerDemo {

public static void main(String[] args)
{
ShareData sd = new ShareData();

new Thread(() -> {
for (int i = 1; i <=10; i++)
{
try {
sd.increment();
Thread.sleep(200);
} catch (Exception e) {
e.printStackTrace();
}
}
},"A").start();

new Thread(() -> {
for (int i = 1; i <=10; i++)
{
try {
sd.decrement();
Thread.sleep(300);
} catch (Exception e) {
e.printStackTrace();
}
}
},"B").start();
new Thread(() -> {
for (int i = 1; i <=10; i++)
{
try {
sd.increment();
Thread.sleep(400);
} catch (Exception e) {
e.printStackTrace();
}
}
},"C").start();

new Thread(() -> {
for (int i = 1; i <=10; i++)
{
try {
sd.decrement();
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
},"D").start();

}
}


线程通信问题

标签:tran   唤醒   get   stat   ons   throw   现在   new t   static   

原文地址:https://www.cnblogs.com/liuyi13535496566/p/12105309.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!