zoukankan      html  css  js  c++  java
  • java线程间通信1--简单实例

    线程通信

     

      一、线程间通信的条件

        1、两个以上的线程访问同一块内存

         2、线程同步,关键字 synchronized

      二、线程间通信主要涉及的方法

        wait();    ----> 用于阻塞进程

        notify();   ----> 用于唤醒进程

        notifyAll();  ----> 用于唤醒所有进程

      三、线程通信的图解

        

      四、线程通信的实例代码

          

     1 //主线程
     2 public class ThreadMain {
     3     
     4     public static void main(String[] args) throws InterruptedException {
     5         Buffer buffer = new Buffer();
     6         
     7         Thread_one thread_one  = new Thread_one(buffer);
     8         thread_one.start();     //启动子线程
     9         
    10         Thread.sleep(1000);      //主线程睡眠1秒
    11         
    12         String name = Thread.currentThread().getName();
    13         System.out.println(name);
    14         buffer.doNotify();         //唤醒子线程
    15     }
    16 }

     

     1 //要访问的内存区
     2 public class Buffer {
     3     
     4     //进行包装
     5     public synchronized void doWait() {
     6         try {
     7             wait();
     8         } catch (InterruptedException e) {
     9             // TODO Auto-generated catch block
    10             e.printStackTrace();
    11         }
    12     }
    13     public synchronized void doNotify() {
    14         notify();
    15     }
    16 }

     

     1 //子线程
     2 public class Thread_one extends Thread{
     3     private Buffer buffer;
     4     public Thread_one(Buffer buffer) {
     5         this.buffer = buffer;
     6     }
     7     @Override
     8     public void run() {
     9         //子线程睡眠
    10         buffer.doWait();
    11         //具体操作,显示当前线程名
    12         String name = Thread_one.currentThread().getName();
    13         System.out.println(name);
    14     }
    15 }

     

  • 相关阅读:
    UVALive
    训练指南 UVA
    训练指南 UVALive
    Codeforces Round #535 (Div. 3)
    训练指南 UVALive
    训练指南 UVALive
    Codeforces Round #534 (Div. 2)
    Codeforces Round #532 (Div. 2)
    《算法问题实战策略》——chaper9——动态规划法技巧
    《训练指南》——8.3
  • 原文地址:https://www.cnblogs.com/lrj1009IRET/p/8479958.html
Copyright © 2011-2022 走看看