使用Java线程创建一个简单队列
我正在尝试使用Java线程创建一个简单的队列,该队列允许一个循环,比如一个10次迭代的for循环,一次迭代n(<10)个线程,并等待这些线程完成后再继续迭代 这里有一个更好的方法来说明我的问题:使用Java线程创建一个简单队列,java,multithreading,queue,Java,Multithreading,Queue,我正在尝试使用Java线程创建一个简单的队列,该队列允许一个循环,比如一个10次迭代的for循环,一次迭代n(
for (int i = 1; i <= 10; i++) {
new Thread ( do_some_work() );
if ( no_available_threads ) {
wait_until_available_threads();
}
}
do_some_work() {
// do something that takes a long time
}
for(int i=1;i我会使用Java 5,而不是您自己的
ExecutorService service = Executors.newFixedThreadPool(10);
// now submit our jobs
service.submit(new Runnable() {
public void run() {
do_some_work();
}
});
// you can submit any number of jobs and the 10 threads will work on them
// in order
...
// when no more to submit, call shutdown, submitted jobs will continue to run
service.shutdown();
// now wait for the jobs to finish
service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
请参阅java.util.concurrent,尤其是Executors和ExecutorService,按照其他人的建议使用Executors。不过,如果您想自己体验一下这样做的乐趣,请尝试以下方法。(当心。我在记事本上写的,即使我把其他一切都做好了,你也需要捕捉一些例外情况。记事本在捕捉编码错误方面很差。)这与其说是解决任何问题的实际方案,不如说是一个概念,但这个想法通常是有用的
private ConcurrentLinkedQueue<MyThread> tQueue =
new ConcurrentLinkedQueue<MyThread>();
class MyThread extends Thread {
public Runnable doSomething;
public void run() {
// Do the real work.
doSomething();
// Clean up and make MyThread available again.
tQueue.add( mythread );
// Might be able to avoid this synch with clever code.
// (Don't synch if you know no one's waiting.)
// (But do that later. Much later.)
synchronized (tQueue) {
// Tell them the queue is no longer empty.
tQueue.notifyAll();
}
}
}
专用ConcurrentLinkedQueue TQUUE=
新建ConcurrentLinkedQueue();
类MyThread扩展线程{
公共运行剂量测量;
公开募捐{
//做真正的工作。
doSomething();
//清理并使MyThread再次可用。
添加(mythread);
//可能可以通过巧妙的代码避免这种同步。
//(如果您知道没有人在等待,请不要同步。)
//(但要晚一点做,要晚得多。)
已同步(TQUUE){
//告诉他们队列不再是空的。
tQueue.notifyAll();
}
}
}
其他地方:
// Put ten MyThreads in tQueue.
for (int i = 0; i < 10; i++) tQueue.add( new MyThread() );
// Main Loop. Runs ten threads endlessly.
for (;;) {
MyThread t = tQueue.poll();
if (t == null) {
// Queue empty. Sleep till someone tells us it's not.
do {
// There's a try-catch combo missing here.
synchonized( tQueue ) { tQueue.wait() };
t = tQueue.poll();
} while (t == null) break; // Watch for fake alert!
}
t.doSomething = do_some_work;
t.start();
}
//在TQUUE中放入十个MyThreads。
对于(inti=0;i<10;i++)tQueue.add(newmythread());
//主循环。无休止地运行十个线程。
对于(;;){
MyThread t=tQueue.poll();
如果(t==null){
//空着排队。睡到有人告诉我们不是。
做{
//这里少了一个试抓组合。
已同步(tQueue){tQueue.wait()};
t=tQueue.poll();
}while(t==null)break;//注意假警报!
}
t、 doSomething=做一些工作;
t、 start();
}
另外,请注意ConcurrentLinkedQueue的巧妙使用。您可以使用ArrayList或LinkedList等其他工具,但需要同步它们。CrateLogger.class
:
public class Logger extends Thread {
List<String> queue = new ArrayList<String>();
private final int MAX_QUEUE_SIZE = 20;
private final int MAX_THREAD_COUNT = 10;
@Override
public void start() {
super.start();
Runnable task = new Runnable() {
@Override
public void run() {
while (true) {
String message = pullMessage();
Log.d(Thread.currentThread().getName(), message);
// Do another processing
}
}
};
// Create a Group of Threads for processing
for (int i = 0; i < MAX_THREAD_COUNT; i++) {
new Thread(task).start();
}
}
// Pulls a message from the queue
// Only returns when a new message is retrieves
// from the queue.
private synchronized String pullMessage() {
while (queue.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {
}
}
return queue.remove(0);
}
// Push a new message to the tail of the queue if
// the queue has available positions
public synchronized void pushMessage(String logMsg) {
if (queue.size() < MAX_QUEUE_SIZE) {
queue.add(logMsg);
notifyAll();
}
}
}
公共类记录器扩展线程{
列表队列=新的ArrayList();
私有最终整数最大队列大小=20;
私有最终整数最大线程数=10;
@凌驾
公开作废开始(){
super.start();
Runnable任务=新的Runnable(){
@凌驾
公开募捐{
while(true){
String message=pullMessage();
Log.d(Thread.currentThread().getName(),message);
//再做一次处理
}
}
};
//创建一组线程以进行处理
对于(int i=0;i
然后在主类中插入以下代码:
Logger logger =new Logger();
logger.start();
for ( int i=0; i< 10 ; i++) {
logger.pushMessage(" DATE : "+"Log Message #"+i);
}
Logger=新的记录器();
logger.start();
对于(int i=0;i<10;i++){
logger.pushMessage(“日期:“+”日志消息#“+i”);
}
非常适合使用ConcurrentLinkedQueue的工作站点,为什么要同步它?