zoukankan      html  css  js  c++  java
  • java wait 和notify

    这几天自己学习了一下线程的知识,wait 方法使当前的线程等待,notify 方法 唤醒当前的线程的方法 

    th 线程在5的时候进行wait,此时主线程继续执行, 主线程执行到9的时候 唤醒 th 线程


    public class ThreadDemo1 {
    public static void main(String[] args) {
      MyThread1 t= new MyThread1();
      Thread th = new Thread(t);
      th.start(); //开启这个线程

    //主线程

    synchronized (th) {
        for(int j=0;j<10;j++){
          try {
          Thread.sleep(1000); //主线程休眠1000毫秒
          if(j==9){
            t.awake();
          }
          System.out.println(Thread.currentThread().getName()+"___"+j);
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
    }

    }

    }

    }


    class MyThread1 implements Runnable{
    private int j = 0;

    //线程执行完后获取j的值
    public int getJ() {
    return j;
    }


    @Override
    public void run() {
    // TODO Auto-generated method stub

    synchronized (this) {
      for(int i = 0;i<10;i++){
        try {
          Thread.sleep(1000); //睡眠1000毫秒,让出cpu的时间片
          System.out.println(Thread.currentThread().getName()+"___"+i);
          if(i==5){
          wait();//线程休眠
         }
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }


    }


    }


    public void awake(){
    synchronized (this) {
    this.notify();
    }

    }

    }

  • 相关阅读:
    JS判断页面是否加载完成
    简单的前端验证码
    如何让旧浏览器支持HTML5新标签
    JSON使用(4)
    JSON语法(3)
    JSON简介(2)
    JSON教程(1)
    jQuery-noConflict()
    jQuery
    jQuery
  • 原文地址:https://www.cnblogs.com/lilefordream/p/3880844.html
Copyright © 2011-2022 走看看