【问题标题】:Java Thread Synchronization 101Java线程同步101
【发布时间】:2020-04-30 08:04:28
【问题描述】:

认为共享对象Control 会强制n 线程(Number)按顺序显示,但显然它们不会:

编号:

public class Number implements Runnable {

    private int i_;
    private Control control;

    public Number(int i, Control c) {
        i_ = i;
        control = c;
    }

    public void start() {
        new Thread(this).start();
    }

    public void run() {
        synchronized(control) {
            control.call(i_);
        }
    }
}

控制:

public class Control {

    private int i_ = 0;

    public void call(int i) {

        if(i != i_) {
            try {
                wait();
            }
            catch(Exception e) {}
        }

        System.out.println(i);
        i_++; // next, please                                                                                                                                                                                   
        notify();
    }
}

测试工具(主要):

public class RunNumbers {

    public static void main(String args[]) {

        int n = 0;
        if (args.length > 0) {
            n = Integer.parseInt(args[0]);
        }

        Control c = new Control();
        for(int i = 0; i < n; ++i) {
            new Number(i, c).start();
        }
    }
}

有什么想法吗?

【问题讨论】:

    标签: java-threads thread-synchronization shared-objects


    【解决方案1】:

    上述内容是通过将几个仅涉及一对线程的教程拼凑而成的(实际上并不知道发生了什么)——导致无法将所有内容扩展到两个以上的线程。

    经过一番研究,可以通过更改Control.java中的两行来解决上述问题:

    (a) 将if(i != i_) { 更改为while(i != i_) {

    (b) 将notify(); 更改为notifyAll();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多