Javaの虚偽の目覚めとどのように虚偽の目覚めを避けるのか.『マルチスレッド学習の14』
15768 ワード
何が目覚めたの?
偽りの呼び覚ましを避ける
次に、虚偽の起動を回避する例を示します.
どうやって虚偽の目覚めを起こすの?
なぜifは偽りの覚醒が現れるのか
, , ,
1. , , ,
, , ,
偽りの呼び覚ましを避ける
次に、虚偽の起動を回避する例を示します.
package duoxiancheng.bao;
/*
* :
* wait while 。
*/
public class LockTest {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Producter producter = new Producter(clerk);
Customer customer = new Customer(clerk);
new Thread(producter," A").start();
new Thread(customer," A").start();
new Thread(producter," B").start();
new Thread(customer," B").start();
}
}
//
class Clerk {
private int product = 0;
//
public synchronized void add() {
//
while (product >=1) {
System.out.println(Thread.currentThread().getName() + ": " + " !");
try {
this.wait();
} catch (InterruptedException e) {
}
}
++product;
// while ,
System.out.println(Thread.currentThread().getName() + ": " +".................... , "+product);
this.notifyAll();
}
//
public synchronized void sale() {
while (product <=0) {
System.out.println(Thread.currentThread().getName() + ": " + " ");
try {
this.wait();
} catch (InterruptedException e) {
}
}
--product;
System.out.println(Thread.currentThread().getName() + ": , " + product);
this.notifyAll();
}
}
//
class Producter implements Runnable {
private Clerk clerk;
public Producter(Clerk clerk) {
this.clerk = clerk;
}
//
@Override
public void run() {
for(int i = 0; i < 20; ++i) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
clerk.add();
}
}
}
//
class Customer implements Runnable {
private Clerk clerk;
public Customer(Clerk clerk) {
this.clerk = clerk;
}
//
@Override
public void run() {
for(int i = 0; i < 20; ++i) {
clerk.sale();
}
}
}
どうやって虚偽の目覚めを起こすの?
while (product >=1) {}
if (product >=1) {}
なぜifは偽りの覚醒が現れるのか
if , if()
while , while()