以下是我的代码。我期待t1和t2应该并行运行但是在完成t1之后,t2开始了。我做错了什么。实际上我正试图复制生产者和消费者的问题,但是我正在制造一些混乱的地方。
import java.util.ArrayList;
import java.util.List;
public class BankThread {
static List<String> amount = new ArrayList<String>();
public static void main(String[] args) {
Deposit dep = new Deposit();
WithDraw wDraw = new WithDraw();
Thread t1 = new Thread(dep);
Thread t2 = new Thread(wDraw);
t1.start();
t2.start();
}
}
class Deposit extends BankThread implements Runnable {
public void run(){
for (int i = 1; i < 10; i++) {
amount.add(""+(i*100));
System.out.println("Deposit #" + i
+ " put: " + i);
try {
Thread.sleep((int)(1000));
} catch (InterruptedException e) { }
}
}
}
class WithDraw extends BankThread implements Runnable{
public void run(){
System.out.println("In withdraw"+amount.size());
try {
for (int i = 0; i< amount.size(); i++) {
System.out.println("Withdraw #" + amount.get(i)
+ " removed " + amount.remove(i));
Thread.sleep((int)(1000));
}} catch (InterruptedException e) { }
}
}
答案 0 :(得分:1)
当我运行它时,输出是:
Deposit #1 put: 1
In withdraw1
Withdraw #100 removed 100
Deposit #2 put: 2
Deposit #3 put: 3
Deposit #4 put: 4
Deposit #5 put: 5
Deposit #6 put: 6
Deposit #7 put: 7
Deposit #8 put: 8
Deposit #9 put: 9
所以他们确实并行运行。问题是撤销只通过循环一次,这可能不是我想要的。
原因是它在for循环开始时查看一次的大小,因此它看不到新项目。