【问题标题】:In java, How to access values of a class from other classes in thier differrent individual threads?在java中,如何从不同的单独线程中的其他类访问一个类的值?
【发布时间】:2020-11-14 15:24:08
【问题描述】:

我有一个名为“时钟”的类,它实现了 Runnable。在 run() 中启动了一个无限循环,其中线程每次迭代都会休眠 100 毫秒,然后更改一个布尔值:“isOk”。

在其单独的线程中有另一个类“ConOne”也有无限循环,它试图从“时钟”类中获取“isOk”布尔值。但如果值为 false,则“ConOne”必须在线程处等待才能继续。

所以我创建了 ConOne 对象,试图从“时钟”类访问布尔值。 但它引发了一个描述“当前对象不是线程所有者”的异常。

为什么会这样? 对不起我的英语。

代码如下: 时钟类

public class Clock implements Runnable {
    boolean isOk;
    Thread t;
    
    Clock() {
        isOk = false;
        t = new Thread(this, "Clock_Thread");
    }
    
    void startClock() {
        t.start();
    }
    
    public void run() {
        int i = 0;
        while(true) {
            try {
                t.sleep(100);
                System.out.println("Tick:" + i);
                if(isOk) {
                    isOk = false;
                } else {
                    isOk = true;
                    notify();
                }
                i++;
            } catch(InterruptedException ie) {
                System.out.println("InterruptedException at Clock");
            }
        }
    }
    
    public boolean getPermit() {
        if (!isOk) {
            try {
                wait();
            } catch(InterruptedException e) {
                System.out.println("Exception at clock.getPermit()");
            }
        }
        return true;
    }
}

ConOne 类:

public class ConOne implements Runnable {
    Thread t;
    Clock ct;
    
    ConOne(String name, Clock c) {
        t = new Thread(this, name);
        ct = c;
    }
    
    public void run() {
        while(true) {
            ct.getPermit();
            repaint();
        }
    }
    
    public void repaint() {
        System.out.println("Repainted On " + t);
    }
}

带有main方法的类:

public class Master {
    public static void main(String[] args) {
        Clock clock = new Clock();
        ConOne con1 = new ConOne("Con11", clock);
        ConOne con2 = new ConOne("Con12", clock);
        
        clock.startClock();
        con1.t.start();
        con2.t.start();
    
        
    }
}

这是错误: Error Screenshot

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

    如果您已在该对象上同步,您只能在该对象上调用等待。

    所以是这样的:

    synchronized(monitor){
       while(!condition)
          monitor.wait();
    }
    

    【讨论】:

      【解决方案2】:

      恐怕你的事情有点曲解了,notify() 和 wait() 需要 Clock 对象的监视器的所有权。您可以尝试使等待/通知语义正确,但我建议仅使用内置工具,特别是 SynchronizedQueue。时钟可以只保存一个作为字段,并在 isOk 时将 1 放入其中。另一个线程可以通过队列中的一个简单的 take() 被放入一个不忙的 wait() 中,这将阻塞直到 Clock 类放入一些东西。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-15
        • 1970-01-01
        • 1970-01-01
        • 2017-09-29
        相关资源
        最近更新 更多