java - 使用Runnable进行并行执行

标签 java multithreading runnable

我编写了这个简单的代码来测试 Runnable 接口(interface)。

    import java.util.List;
    import java.util.ArrayList;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    class myClass implements Runnable{
      private final List< String >[] ls;
      private int n;
      public myClass(int m) 
      { 
        n = m;
        ls = new List[n];
        for (int i = 0; i < n; i++) {
          ls[i] = new ArrayList<>();
        }
      }
      public void run()
      {
        try {
          for (int i = 0; i < n; i++) {
            pleasePrint( ls[i] );
          } 
        } catch (Exception e) {
            System.out.println("error");
        }
      }
      public void init() {

        ls[0].add("1");  ls[0].add("2");  ls[0].add("3");
        ls[1].add("4");  ls[1].add("5");  ls[1].add("6");
      }
      void pleasePrint( List< String > ss )
      {
        for (int i = 0; i < ss.size(); i++) {
          System.out.print(ss.get(i)); // print the elements of one list
        }
      }
    }

    public class Threadtest {
      public static void main(String[] args) {
        myClass mc = new myClass(2);
        mc.init();
        ExecutorService te = Executors.newCachedThreadPool();
        te.execute(mc);
        te.shutdown();
      }
    }

当我运行代码时,它将打印 123456。如何确定两个线程并行运行?根据给定的输出,它们可能正在串行模式下运行!

最佳答案

在您给出的示例中,仅启动了一个线程。

要将多个任务提交到 ExecutorService,请使用 submit() 方法:

ExecutorService te = Executors.newCachedThreadPool();
te.submit(task);
te.submit(anotherTask);
// Some code
te.shutdown();

要检查(出于学习目的)线程是否不同,请在 run() 中打印线程的名称:

String name = Thread.currentThread().getName();

我头顶的解决方案:

public void run() {
    String name = Thread.currentThread().getName();
    System.out.println(name);

    // Do Something
}

如果我向 ExecutorService 提交同一个实例两次:

public static void main(String[] args) {
    myClass mc = new myClass(2);
    mc.init();
    ExecutorService te = Executors.newCachedThreadPool();
    te.submit(mc);
    te.submit(mc);
    te.shutdown();
}

然后输出:

pool-1-thread-1
1
2
3
4
5
6
pool-1-thread-2
1
2
3
4
5
6

注意:我将 print() 更改为 println() 并在 run()< 中打印了线程的名称.

希望这有帮助。


更新#1

要从不同线程打印列表,您需要更改方法。调用 pleasePrint() 的循环需要生成一个新线程,然后从该线程调用此方法。

关于java - 使用Runnable进行并行执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44084063/

相关文章:

java - 动态显示附加文本的 TextArea

Java线程似乎无法正常运行

java - 打印数组

android opengl es 在两个线程上运行的两个上下文之间共享纹理

c++ - 如何在具有 <500 MHz 时钟、<256 MiB RAM 并使用基于 Yoctominimal 的自定义 Linux 的单核机器上优化事件轮询线程

Java 两个 Web 服务调用并发以获得更好的性能

java - 播放不间断的声音声音池

java - 如何在 Spring data Neo4j 4 中定义命名查询

java - 在java中使用接口(interface)或类型定义变量?

java - 提示用户继续不工作,java