简体   繁体   English

在Java中使用多个线程

[英]Using more than one thread in Java

I'm new to concurrent programing and have been working on code which has a queue of items to be processed, this is passed to some worker threads, the number specified by the user. 我是并发编程的新手,并且一直致力于处理具有要处理的项目队列的代码,这将传递给一些工作线程,即用户指定的编号。 At the moment I've just tried to do it with two worker threads plus the main. 目前我刚尝试用两个工作线程加上主线程。

private static class workerThread extends Thread {

        workerThread(){
            super();
        }


        public void run(){
             while (!workQueue.isEmpty()) {

            String x = workQueue.remove();
            //System.out.println("work queue size: " + workQueue.size());
            Vector<String> list2 = new Vector<String>((Vector) table.get(x));
            list2 = process(x, list2);
            //System.out.println(list2 + "list2");
            table.put(x, list2);

            //System.out.println(x + "key" + "value" + vvv);

        }

        }

That's the thread workerthread class, I've tried to call it just by creating two new threads: 这是线程workerthread类,我试图通过创建两个新线程来调用它:

workerThread wt = new workerThread();
    workerThread wt2 = new workerThread();
    wt.start();
    wt2.start();
    try {
        wt.join();
        wt2.join();
    } catch (InterruptedException ex) {
        Logger.getLogger(includeCrawler.class.getName()).log(Level.SEVERE, null, ex);
    }

I'm not sure if this is right, or will have any benfit due to waiting for the joins? 我不确定这是不对的,还是因为等待连接会有什么好处? Thanks for any help. 谢谢你的帮助。

A much cleaner and scalable way to do this is to use a thread pool created by the Executors class. 更简洁和可扩展的方法是使用Executors类创建的线程池。

By the way, the Vector class is obsolete and should not be used anymore - use ArrayList instead and dump whatever book or tutorial where you learned to use Vector - it's more than a decade out of date. 顺便说一句, Vector类已经过时,不应该再使用了 - 使用ArrayList代替并转储你学习使用Vector任何书籍或教程 - 它已经过时了十多年。

Just a few references, I think you want to use a BlockingQueue along with an ExecutorService and a Runnable or Callable . 只是一些参考,我想你想使用BlockingQueue以及ExecutorServiceRunnableCallable

final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); perhaps even an instance variable (private static final ExecutorService POOL = ...). 甚至可能是一个实例变量(私有静态最终ExecutorService POOL = ...)。 For an I/O bound application you might want to use more threads than the available processors. 对于I / O绑定的应用程序,您可能希望使用比可用处理器更多的线程。 Then again you don't want to use Vector . 然后你又不想使用Vector Use another List implementation (usually ArrayList is the one to use). 使用另一个List实现(通常使用ArrayList )。

BTW: If you want to master concurrent programming you might also want to read about Akka and Actors/STM instead of using the usual shared mutability model. 顺便说一句:如果你想掌握并发编程,你可能还想阅读有关Akka和Actors / STM而不是使用通常的共享可变性模型。

Edit: I would definately recommend http://pragprog.com/book/vspcon/programming-concurrency-on-the-jvm and Effective Java from Josh(ua) Bloch. 编辑:我肯定会推荐来自Josh(ua)Bloch的http://pragprog.com/book/vspcon/programming-concurrency-on-the-jvm和Effective Java。

You definitely have to use Executors. 你肯定要使用Executors。 This is an example just for reference. 这是一个仅供参考的示例。 It works on a single thread, but I think it's a good start for you. 它适用于单个线程,但我认为这对你来说是一个好的开始。 It's easily adaptable to an arbitrary number of threads. 它很容易适应任意数量的线程。

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<MyObject> f =
    executor.submit(new Callable<MyObject>() {

      @Override
      public MyObject call() throws Exception {
        MyObject obj = new MyObject();
        // do stuff
        return obj;
      }

    });

MyObject myObject =
    new MyObject();

try {
  myObject = f.get(500, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e) {
  // stuff
}
catch (ExecutionException e) {
  // stuff
}
catch (TimeoutException e) {
  // stuff
}
finally {
  executor.shutdown();
}

In this case I wanted to wait at most 500ms before timeout, but this is optional. 在这种情况下,我想在超时之前等待最多500ms,但这是可选的。 Hope this could help. 希望这可以帮助。

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

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