[英]Print ArrayList sequentially using two threads in Java
下面的代碼如何是錯誤編碼的示例,我們如何改進它? 請幫助我理解它。
問題:使用兩個線程順序打印 ArrayList
我的代碼: -
public class xyz {
public static void main(String[] args) throws InterruptedException {
ArrayList<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
Thread odd = new Thread(() -> {
for (int i = 0; i < list1.size(); i = i + 2) {
synchronized (list1) {
System.out.println(Thread.currentThread().getName() + " : " + list1.get(i));
list1.notifyAll();
try {
list1.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
Thread even = new Thread(() -> {
for (int i = 1; i < list1.size(); i = i + 2) {
synchronized (list1) {
System.out.println(Thread.currentThread().getName() + " : " + list1.get(i));
list1.notifyAll();
try {
list1.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
odd.setName("Odd");
even.setName("Even");
odd.start();
even.start();
odd.join();
even.join();
}
}
結果 -
奇數:1 偶數:2 奇數:3 偶數:4 奇數:5 偶數:6 奇數:7 偶數:8 奇數:9 偶數:10
這是糟糕的編碼,因為它使用多個線程按順序執行某些操作……除此之外。
彈出的內容是wait
不在while
循環中。 總是(幾乎)把wait
放在一個while
循環中。 如果你有一個谷歌,可能有很好的參考 - 我仍然會為 Doug Lea 的並發編程 go 在 Java上個世紀的第二版。
使用java.util.concurrent
可能有更好的方法 - 請參閱Java Concurrency In Practice 。
您將需要某種共享的 state 來指示應該執行哪個線程。 檢查你的while
條件。
我注意到它是從鎖外調用size
的。 雖然這可能沒問題,但您調用的是非線程安全的可變 object。
真正可怕的是大部分代碼都是重復的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.