基于synchronized同步关键字的wait、notify实现生产者消费者的并发控制

Java artisan 362℃ 0评论

package com.javartisan; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; class TSafeList { private List<Integer> q = new ArrayList<>(); private int size = 5; public void add(Integer value) { synchronized (q) { while (q.size() >= size) { try { q.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } q.add(value); // 有元素了之后需要再次进行唤醒消费 q.notifyAll(); } } public Integer poll() { synchronized (q) { while (q.size() <= 0) { try { q.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Integer e = q.remove(0); q.notifyAll(); return e; } } } public class Main { public static void main(String[] args) throws InterruptedException { Set<Integer> set = new HashSet<>(); AtomicInteger atomicInteger = new AtomicInteger(0); AtomicInteger result = new AtomicInteger(0); TSafeList tSafeList = new TSafeList(); Thread t1 = null; Thread t2 = null; for (int i = 0; i < 50; i++) { Thread t = new Thread(new Runnable() { @Override public void run() { for (int j = 0; j < 10; j++) { Integer poll = tSafeList.poll(); synchronized (set) { //仅仅验证测试结果 set.add(poll); } result.getAndIncrement(); System.out.println(Thread.currentThread().getName() + " poll " + poll + " poll size = " + result.get()); } } }); t.start(); if (i == 49) { t1 = t; } } for (int i = 0; i < 50; i++) { Thread t = new Thread(new Runnable() { @Override public void run() { for (int j = 0; j < 10; j++) { tSafeList.add(atomicInteger.getAndIncrement()); } } }); t.start(); if (i == 49) { t2 = t; } } t1.join(); t2.join(); Thread.sleep(1000); System.out.println("set size " + set.size()); System.out.println("DONE"); } }

转载请注明:Java工匠师 » 基于synchronized同步关键字的wait、notify实现生产者消费者的并发控制

喜欢 (4)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址