问题描述
- condition.await()并发问题
-
public class BlockArrayList extends ArrayList
{
/*** long serialVersionUID:TODO(用一句话描述这个变量表示什么)
*
* @since 1.0.0
*/
private static final long serialVersionUID = 1L;
private ReentrantLock lock = new ReentrantLock(); private Condition notEmpty = lock.newCondition(); public int i = 0; public Exception ee; public E take() throws InterruptedException { try { lock.lock(); E e = null; int size = this.size(); if(size == 0) { notEmpty.await(); } i++; System.out.println(i); try { e = this.remove(0); } catch(Exception e1) { ee = e1; } return e; } finally { lock.unlock(); } } public boolean offer(E e) { try { lock.lock(); this.add(e); notEmpty.signal(); return true; } finally { lock.unlock(); } } public void op() { E s = null; try { s = this.take(); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName() +" 被动结束"); e.printStackTrace(); } } public class MyThreadFactory implements ThreadFactory { private AtomicInteger NUMBER = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("shaoweiThread-"+NUMBER.decrementAndGet()); return t; } } public static void main(String[] args) { final BlockArrayList<String> list = new BlockArrayList<String>(); ThreadFactory threadThread = list.new MyThreadFactory(); Thread t = threadThread.newThread(new Runnable() { @Override public void run() { int i = 0; while(i <410000) { list.op(); } } }); t.start(); threadThread.newThread(new Runnable() { @Override public void run() { int i = 0; while(i <410000) { list.op(); } } }).start(); threadThread.newThread(new Runnable() { @Override public void run() { for(int i=0;i<400000;i++) { boolean flag = list.offer("item" + i); if(!flag) { System.out.println("添加元素失败"); } } System.out.println(list.ee); } }).start(); System.out.println("主线程结束"); }
}
多个线程去取阻塞队列为啥会有并发问题呢?i正常应该为400000的,谁能给解释下
解决方案
但是现在的值为402235
解决方案二:
while(i <410000)
{
synchronized (list) {
list.op();
}
}
list没有做线程安全同步,使用synchronized进行安全处理。
时间: 2024-10-06 13:25:04