【发布时间】: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