【发布时间】:2019-04-15 16:53:22
【问题描述】:
我的数据量很大,所以我想把它分成块并使用线程来异步处理它。 为了简单起见,假设我有一个列表并将每个条目与一个线程相关联,因此线程数等于元素数。由于我是 Java 线程的新手,所以我不确定线程是如何异步运行的。这是一个简化的代码,以便更好地理解。
class ThreadRunner extends Thread {
String threadName;
String element;
public MyThread (String threadName, String element) {
this.threadName = threadName;
this.element = element;
}
public void run() {
System.out.println("Run: "+ threadName);
// some processing on the item
}
}
class TestThread {
public static void main (String arg[]) {
List<String> mainList = new ArrayList<>();
for (int x=0; x< mainList.size(); x++)
{
MyThread temp= new MyThread("Thread #" + x+1);
temp.start();
System.out.println("Started Thread:" + x+1);
}
}
此代码是否以异步方式执行线程?
【问题讨论】:
-
你认为为什么会这样?为什么你认为它没有?您是否以某种方式收集了任何证据?
-
我尝试运行,但线程正在同步运行。例如,如果我们改变上面的代码,让每个线程处理 2 个元素。然后第二个线程在第一个线程完成后运行。那么我的逻辑有问题吗?
-
可能会添加更多元素。
-
目前我在每个线程中有大约 4000 个元素。
-
您没有看到任何交错的打印消息(您应该在处理元素的循环中的某处有一个日志)?
标签: java multithreading concurrency