Thread faculty = new Thread(() -> {
try {
while (true) {
boolean is_grab = false;
semp.acquire();
if (candy > 0) {
System.out.println("No." + NO + " faculty grabs a candy");
candy--;
is_grab = true;
System.out.println("Candy num left:" + candy);
}
semp.release();
if (is_grab) {
Thread.sleep(1000);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
faculty.start();
}
In the code above, I use a semaphore implementation for synchronization and if (is_grab) { Thread.sleep(1000); } could be executed.
However, in code below,
Thread faculty = new Thread(() -> {
synchronized (Bowl.class) {
while (true) {
while (Bowl.candy <= 0) {
try {
Bowl.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("No." + NO + " faculty grabs a candy");
Bowl.candy--;
System.out.println("Candy num left:" + Bowl.candy);
Bowl.class.notifyAll();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
I use synchronized on Bowl.class but try{sleep} is unreachable. Why?
在下面的示例中,没有break
语句可以退出while(true)
循环。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.