We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
package com.ph.juc;
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;
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(); } // 2. 干活 number++; System.out.println(Thread.currentThread().getName() + "\t " + number); // 3.通知、唤醒 condition.signalAll(); }catch(Exception e){ e.printStackTrace(); }finally{ lock.unlock(); } } public void decrement() throws Exception{ lock.lock(); try{ // 1. 判断 while (number == 0){ // 等待不能生产 condition.await(); } // 2. 干活 number--; System.out.println(Thread.currentThread().getName() + "\t " + number); // 3.通知、唤醒 condition.signalAll(); }catch(Exception e){ e.printStackTrace(); }finally{ lock.unlock(); } }
}
/**
*/ public class ProdConsumer_TraditionDemo {
public static void main(String[] args) throws Exception{ ShareData shareData = new ShareData(); new Thread(()->{ for (int i = 1; i <= 5; i++) { try { shareData.increment(); } catch (Exception e) { e.printStackTrace(); } } },"AA").start(); new Thread(()->{ for (int i = 1; i <= 5; i++) { try { shareData.decrement(); } catch (Exception e) { e.printStackTrace(); } } },"BB").start(); }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
package com.ph.juc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ShareData{
private int number = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
}
/**
*/
public class ProdConsumer_TraditionDemo {
}
The text was updated successfully, but these errors were encountered: