繁体   English   中英

使用 Java 线程创建一个简单的队列

[英]Create a simple queue with Java threads

我正在尝试使用 Java Thread 创建一个简单的队列,该队列将允许循环,例如具有 10 次迭代的 for 循环,一次迭代 n (< 10) 个线程并等到这些线程完成后再继续迭代。

这是一个更好的方法来说明我的问题:

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
}

基本上我想做的是一个副本: 线程和队列

我怎样才能以最无痛的方式实现这一目标?

我会使用 Java 5 Executors而不是你自己的。 类似于以下内容:

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);

按照其他人的建议使用 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();
        }
    }
}

别处:

// 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();
}

另外,请注意 ConcurrentLinkedQueue 的巧妙使用。 您可以使用其他类似 ArrayList 或 LinkedList 的东西,但您需要同步它们。

Crate Logger.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();
        }

    }
}

然后在你的主类中插入波纹管代码:

Logger logger =new Logger();
logger.start();
for ( int i=0; i< 10 ; i++) {
    logger.pushMessage(" DATE : "+"Log Message #"+i);
}

参见 java.util.concurrent 尤其是 Executors 和 ExecutorService

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM