想实现wait与notify的互斥,使他们在同步锁当中,这是一种实现互斥的一种
解决方案
下面使用生产者与消费者来演示wait与notify的应用
代码示例:
工厂类
package com. hzh. shopping;
import java. util. LinkedList;
public class ProductFactory {
LinkedList< String> list = new LinkedList < > ( ) ;
int max = 10 ;
public void SaveProduct ( ) {
}
public synchronized void ProduceProduct ( String name) {
while ( list. size ( ) == max) {
try {
this . wait ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
list. add ( name) ;
System. out. println ( Thread. currentThread ( ) . getName ( ) + "生产了" + name+ ",当前商品总数" + list. size ( ) ) ;
if ( list. size ( ) == max) {
try {
this . notifyAll ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
}
public synchronized void ConsumeProduct ( ) {
while ( list. size ( ) == 0 ) {
try {
this . wait ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
String name = list. remove ( 0 ) ;
System. out. println ( Thread. currentThread ( ) . getName ( ) + "消费了" + name+ ",当前商品总数" + list. size ( ) ) ;
if ( list. size ( ) == 0 ) {
this . notifyAll ( ) ;
}
}
}
生产者
package com. hzh. shopping;
public class ProcedureRunnable implements Runnable {
private ProductFactory factory;
public ProcedureRunnable ( ) {
}
public ProcedureRunnable ( ProductFactory factory) {
this . factory = factory;
}
public ProductFactory getFactory ( ) {
return factory;
}
public void setFactory ( ProductFactory factory) {
this . factory = factory;
}
@Override
public void run ( ) {
int i= 0 ;
while ( true ) {
try {
Thread. sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
factory. ProduceProduct ( "商品" + i) ;
i++ ;
}
}
}
消费者
package com. hzh. shopping;
public class ConsumerRunnable implements Runnable {
private ProductFactory factory;
public ConsumerRunnable ( ) {
}
public ConsumerRunnable ( ProductFactory factory) {
this . factory = factory;
}
public ProductFactory getFactory ( ) {
return factory;
}
public void setFactory ( ProductFactory factory) {
this . factory = factory;
}
@Override
public void run ( ) {
while ( true ) {
try {
Thread. sleep ( 300 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
factory. ConsumeProduct ( ) ;
}
}
}
测试类
package com. hzh. shopping;
public class Test {
public static void main ( String[ ] args) {
ProductFactory factory = new ProductFactory ( ) ;
ProcedureRunnable runnable1 = new ProcedureRunnable ( factory) ;
for ( int i = 0 ; i < 10 ; i++ ) {
new Thread ( runnable1, "生产者" + i) . start ( ) ;
}
ConsumerRunnable runnable2 = new ConsumerRunnable ( factory) ;
for ( int i = 0 ; i < 20 ; i++ ) {
new Thread ( runnable2, "消费者" + i) . start ( ) ;
}
}
}
上面的方案很好的解释了wait与notify的应用,当仓库的容量已经满了,这个
时候唤醒沉睡的消费者线程,并且让生产者线程进入wait状态
当仓库的容量为0时,唤醒生产者线程,并且将消费者线程进入wait状态