java 多个线程处理一个对象集合
程序员文章站
2022-06-14 21:41:29
...
好消息,百度网盘专业搜索网站上线了
打开瞧一瞧:http://bitar.cn
打开瞧一瞧:http://bitar.cn
package com.thread; import java.sql.SQLException; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MutiThreadExecutor { /** * @param args * @throws SQLException */ public static void main(String[] args) throws SQLException { MyT t =new MyT(); t.start(10); for (int i = 0; i < 100; i++) { t.triggerEvent(""+i); } } } /** * 多个线程处理一个对象集合(ConcurrentLinkedQueue),没有返回结果 * @author Administrator * */ class MyT implements Runnable{ private static Object lock =new Object(); public static ExecutorService exec=null; boolean running; ConcurrentLinkedQueue<String> eventQueue = new ConcurrentLinkedQueue<String>(); public void start(int threadCount){ running=true; exec = Executors.newFixedThreadPool(threadCount); for (int i = 0; i <threadCount; i++) { exec.submit(this); } } public void stop(){ running=false; } public void triggerEvent(String str) { synchronized (lock) { eventQueue.add(str); lock.notifyAll(); } } @Override public void run() { while (running) { synchronized (lock) { if (eventQueue.isEmpty() && running) { try { lock.wait(1000 * 30 );//超时30秒 } catch (InterruptedException ie) { } } } while (!eventQueue.isEmpty()) { String event = (String) eventQueue.poll(); if (null != event) { System.out.println(Thread.currentThread().getId()+":"+event); } } } } }
下一篇: 黑莓Q5 8月13日登陆加拿大
推荐阅读