zoukankan      html  css  js  c++  java
  • 线程交互-> 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、生产者和消费者问题(待续)

  • 相关阅读:
    .net百度编辑器的使用
    phpstudy远程连接mysql
    HDU-2389 Rain on your Parade
    HDU-2768 Cat vs. Dog
    HDU-1151 Air Raid
    HDU-1507 Uncle Tom's Inherited Land*
    HDU-1528/1962 Card Game Cheater
    HDU-3360 National Treasures
    HDU-2413 Against Mammoths
    HDU-1045 Fire Net
  • 原文地址:https://www.cnblogs.com/wintersong/p/4752983.html
Copyright © 2011-2022 走看看