【问题标题】:Java threads are not working in parallelJava 线程不能并行工作
【发布时间】:2017-05-08 19:44:47
【问题描述】:

下面是我的代码。我期望 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) { }
        }

    }

【问题讨论】:

标签: java multithreading concurrency


【解决方案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

所以他们确实并行运行。问题是,withdraw 只经历了一次循环,这可能不是我想要的。

原因是它在 for 循环开始时查看了一次 amount 的大小,因此它看不到新项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 2017-10-01
    • 2011-04-04
    • 1970-01-01
    相关资源
    最近更新 更多