我编写了这个简单的代码来测试 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/