java多线程共享变量
import java.util.LinkedList; import java.util.List; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class PC { private static final Lock lock = new ReentrantLock(); private static final Condition empty = lock.newCondition(); private static final Condition full = lock.newCondition(); private static final List<Integer> list = new LinkedList<>(); private static int size = 0; private static int maxSize = 5; private static int product = 1; public static void put() { lock.lock(); try { while (size == maxSize) { empty.await(); } list.add(product); size++; System.out.println("put " + product); product++; full.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public static void take() { lock.lock(); try { while (size == 0) { full.await(); } int tep = list.remove(0); size--; System.out.println("take " + tep); empty.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } class Producer implements Runnable { @Override public void run() { for (int i = 1; i < 10; i++) { put(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Consumer implements Runnable { @Override public void run() { for (int i = 1; i < 10; i++) { take(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { PC pc = new PC(); new Thread(pc.new Producer()).start(); new Thread(pc.new Consumer()).start(); new Thread(pc.new Producer()).start(); new Thread(pc.new Consumer()).start(); } }
put 1 take 1 put 2 take 2 put 3 put 4 put 5 put 6 put 7 take 3 take 4 put 8 put 9 take 5 take 6 put 10 put 11 take 7 take 8 put 12 put 13 take 9 take 10 put 14 put 15 take 11 take 12 put 16 put 17 take 13 take 14 put 18 take 15 take 16 take 17 take 18