chap9-7.txt

来自「JAVA 学习资源」· 文本 代码 · 共 82 行

TXT
82
字号
// 程序9-7
class comm{
    private int n;
    private boolean bool=false;

    synchronized void produce(int i) {
        if(bool) { 	// bool是共享变量,用于控制读取
            try{
                wait( );	// 线程运行到此,将进入等待队列
            }catch(InterruptedException e) {
                System.out.println("comm 中出现了异常");
            }
        }else{
            n=i;
            bool=true;
            System.out.println("\n产生数据: "+n);
            notify( );	// 唤醒另外一个线程
        }
    }

    synchronized void readout( ) {
        if(!bool) {     	// bool是共享变量,用于控制读取
            try{
                wait( );    // 当前线程进入了等待队列
            }catch(InterruptedException e) {
                System.out.println(" comm 中出现了异常");
            }
        }else{
            bool=false;
            System.out.println("读取数据: "+n);
            notify( );	// 唤醒另外一个线程
        }
    }
}

class dataProducer  implements Runnable{ 
    comm cm;
    dataProducer (comm c) {
        cm=c;
    }

    public void run( ) {
        try{
            for(int i=0;i<5;i++) {
                cm.produce((int)(Math.random( )*100));
                Thread.sleep(10);	// 延迟10个毫秒模拟程序执行
            }
        }catch(InterruptedException e) {
            System.out.println("dataProducer 中出现了异常");
        }
    }
}

class dataConsumer implements Runnable{
    comm cm;
    dataConsumer(comm c) {
        cm=c;
    }

    public void run( ) {
        try{
            for(int i=0;i<5;i++) {
                cm.readout( );
        Thread.sleep(10);    	// 延迟10个毫秒模拟程序执行
            }
        }catch(InterruptedException e) {
            System.out.println(" dataConsumer 中出现了异常");
        }
    }
}

public class multTheadFour{
    public static void main(String args[ ]) {
        comm cm=new comm( );
        Thread t1=new Thread(new dataProducer (cm));
        Thread t2=new Thread(new dataConsumer(cm));

        t1.start( );
        t2.start( );
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?