• 线程交互-> wait notify


    1、涉及多线程共享数据操作时,除了同步问题之外,还会遇到另一类问题:如何控制相互交互的线程之间的交互进度。

    举例来说:有两个人,一个在洗碗,一个在擦碗,洗碗的碗放到架子上,如果架子是空的,则擦碗的人进入等待状态,如果架子满了,则洗碗的人进入等待状态。

    public class Test {
       public static void main(String[] args) {
        final f ff=new f();
        new Thread(new Runnable() {        
            @Override
            public void run() {
                while(true){
                ff.f1();
                }
            }
        },"A").start();
        new Thread(new Runnable() {        
            @Override
            public void run() {
                while(true){
                    ff.f2();
                }
            }
        },"B").start();    
    }    
    }
    
    class f{
        boolean flag=false;
    public synchronized void f1() {
        while(flag==true){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        System.out.println(Thread.currentThread().getName());
        flag=true;
        notifyAll();
    }
    public synchronized void f2(){
        while(!flag){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }    
        System.out.println(Thread.currentThread().getName());
        flag=false;
        notifyAll();
      }
    }

    确保了A和B的交替打印。

    2、生产者和消费者问题(待续)

  • 相关阅读:
    SQL Server 存储过程
    FindControl的详细介绍
    Transaction-SQL 游标
    硬盘安装工具nt6 hdd installer无法卸载的问题
    Some question about Source Tree
    java 简单加密
    java 多态与多重继承
    构造方法和方法的重载
    64位WIN7上安装11G R2 ,PLSQL的配置方法
    语录(排名不分先后)
  • 原文地址:https://www.cnblogs.com/wintersong/p/4752983.html
Copyright © 2020-2023  润新知