JAVA线程sleep()和wait()详解及实例

 更新时间:2017年05月12日 09:48:01   投稿:lqh  
这篇文章主要介绍了JAVA线程sleep()和wait()详解及实例的相关资料,探讨一下sleep()和wait()方法的区别和实现机制,需要的朋友可以参考下

JAVA线程sleep()和wait()详解及实例

sleep

1.sleep是Thread的一个静态(static)方法。使得Runnable实现的线程也可以使用sleep方法。而且避免了线程之前相互调用sleep()方法,引发死锁。

2.sleep()执行时需要赋予一个沉睡时间。在沉睡期间(阻塞线程期间),CPU会放弃这个线程,执行其他任务。当沉睡时间到了之后,该线程会自动苏醒,不过此时线程不会立刻被执行,而是要等CPU分配资源,和其他线程进行竞争。

3.此外如果这个线程之前获取了一个机锁,在沉睡期间,这个机锁不会释放。其他等待这个机锁的程序,必须等待这个线程醒来,且执行完后才能运行。

sleep相关代码

public class ThreadTest2 {

  public static void main(String[] args){
    System.out.println("begin our test");
    ThreadSleep sleep = new ThreadSleep();
    try {
      Thread thread1 = new Thread(sleep,"路人甲");
      Thread thread2 = new Thread(sleep,"路人乙");
      thread1.start();
      thread2.start();
    }catch(Exception e){
      e.printStackTrace();
    }
    System.out.println("test is over");
  }


}

 class ThreadSleep implements Runnable{

   int count = 0;

   @Override
   public void run(){
     System.out.println(Thread.currentThread().getName() + " say : hello sleep !!");
     count();

   }

   public void count(){
     while(count < 20) {
         System.out.println(Thread.currentThread().getName() + " say : count is " + count);
         try {
           count++;
           Thread.sleep(100);
         } catch (Exception e) {
           e.printStackTrace();
         }
     }

   }
}

输出日志

begin our test
test is over
路人甲 say : hello sleep !!
路人甲 say : count is 0
路人乙 say : hello sleep !!
路人乙 say : count is 1
路人甲 say : count is 2
路人乙 say : count is 2
路人甲 say : count is 4
路人乙 say : count is 4
路人甲 say : count is 6
路人乙 say : count is 7
路人乙 say : count is 8
路人甲 say : count is 8
路人甲 say : count is 10
路人乙 say : count is 10
路人乙 say : count is 12
路人甲 say : count is 12
路人乙 say : count is 14
路人甲 say : count is 14
路人甲 say : count is 16
路人乙 say : count is 16
路人甲 say : count is 18
路人乙 say : count is 18

通过日志可以发现线程甲和线程乙基本是交替执行,但是并不规律,且出现了并发问题。

该情况是由于代码中设置了睡眠时间为100毫秒,由于count递增执行速度很快,所以线程差不多是同时睡眠,然后同时苏醒并导致了并发的出现。

接下来要添加synchronize块,检查sleep时机锁是否释放

public class ThreadTest2 {

  public static void main(String[] args){
    System.out.println("begin our test");
    ThreadSleep sleep = new ThreadSleep();
    try {
      Thread thread1 = new Thread(sleep,"路人甲");
      Thread thread2 = new Thread(sleep,"路人乙");
      thread1.start();
      thread2.start();
    }catch(Exception e){
      e.printStackTrace();
    }
    System.out.println("test is over");
  }


}

class ThreadSleep implements Runnable{

  int count = 0;

  @Override
  public void run(){
    System.out.println(Thread.currentThread().getName() + " say : hello sleep !!");
    count();

  }

  public void count(){
    while(count < 20) {
      synchronized (this) {
        System.out.println(Thread.currentThread().getName() + " say : count is " + count);
        try {
          count++;
          Thread.sleep(100);
        } catch (Exception e) {
          e.printStackTrace();
        }

      }
    }

  }
}

输出日志

begin our test
路人甲 say : hello sleep !!
路人甲 say : count is 0
test is over
路人乙 say : hello sleep !!
路人甲 say : count is 1
路人甲 say : count is 2
路人甲 say : count is 3
路人甲 say : count is 4
路人甲 say : count is 5
路人甲 say : count is 6
路人甲 say : count is 7
路人甲 say : count is 8
路人甲 say : count is 9
路人甲 say : count is 10
路人甲 say : count is 11
路人甲 say : count is 12
路人甲 say : count is 13
路人甲 say : count is 14
路人甲 say : count is 15
路人甲 say : count is 16
路人甲 say : count is 17
路人甲 say : count is 18
路人甲 say : count is 19
路人乙 say : count is 20

通过日志可以看出,基本是线程甲在执行,这是因为sleep时,机锁一直在线程甲上,所以线程乙只能一直等待直到线程甲释放锁。

wait

1.wait()是Object类的一个方法。当调用wait()方法时,该线程会进入和该对象相关的等待池中,并释放它所拥有的机锁。

2.执行wait()后,必须使用notify()方法或notifyAll()方法或设置等待时间(wait(long time))唤醒在等待线程池中的线程。

3.wait()必须放在synchronized block中,否则会在运行时报“java.lang.IllegalMonitorStateException”异常

wait相关代码

public class ThreadTest2 {

  public static void main(String[] args) {
    System.out.println("begin our test");
    ThreadSleep sleep = new ThreadSleep();
    try {
      Thread thread1 = new Thread(sleep, "路人甲");
      Thread thread2 = new Thread(sleep, "路人乙");
      thread1.start();
      thread2.start();
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println("test is over");
  }
}

class ThreadSleep implements Runnable {

  int count = 0;

  @Override
  public void run() {
    System.out.println(Thread.currentThread().getName() + " say : hello sleep !!");
    count();

  }

  public void count() {
    while (count < 20) {
      synchronized (this) {
        System.out.println(Thread.currentThread().getName() + " say : count is " + count);
        try {
          count++;
          this.wait(100);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

  }
}

输出日志

begin our test
路人甲 say : hello sleep !!
路人甲 say : count is 0
test is over
路人乙 say : hello sleep !!
路人乙 say : count is 1
路人甲 say : count is 2
路人乙 say : count is 3
路人甲 say : count is 4
路人乙 say : count is 5
路人甲 say : count is 6
路人乙 say : count is 7
路人甲 say : count is 8
路人乙 say : count is 9
路人甲 say : count is 10
路人乙 say : count is 11
路人甲 say : count is 12
路人乙 say : count is 13
路人乙 say : count is 14
路人甲 say : count is 15
路人乙 say : count is 16
路人甲 say : count is 17
路人乙 say : count is 18
路人甲 say : count is 19

通过日志可以发现在wait的情况下,机锁会被释放。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

  • java连接数据库知识点总结以及操作应用

    java连接数据库知识点总结以及操作应用

    这篇文章主要给大家介绍了关于java连接数据库知识点总结以及操作应用的相关资料, 当涉及到Java中数据库数据处理时,我们可以利用强大的Java数据库连接技术与各种数据库进行交互,需要的朋友可以参考下
    2023-12-12
  • java接口中的代理设计模式代码时实践

    java接口中的代理设计模式代码时实践

    这篇文章主要介绍了java接口中的代理设计模式代码时实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07
  • 基于Java的正则表达式

    基于Java的正则表达式

    正则表达式,又称正规表示法、常规表示法(英语:Regular Expression,在代码中常简写为regex、regexp或RE),计算机科学的一个概念
    2017-05-05
  • JAVA使用ffmepg处理视频的方法(压缩,分片,合并)

    JAVA使用ffmepg处理视频的方法(压缩,分片,合并)

    这篇文章主要介绍了JAVA使用ffmepg处理视频的方法,包括视频压缩分片合并功能,通过实例代码讲解的很详细,对java ffmepg处理视频相关知识感兴趣的朋友一起看看吧
    2021-05-05
  • struts2实现多文件上传的示例代码

    struts2实现多文件上传的示例代码

    本篇文章主要介绍了struts2实现多文件上传的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-03-03
  • Spring Cloud Ribbon 中的 7 种负载均衡策略的实现方法

    Spring Cloud Ribbon 中的 7 种负载均衡策略的实现方法

    Ribbon 内置了 7 种负载均衡策略:轮询策略、权重策略、随机策略、最小连接数策略、重试策略、可用性敏感策略、区域性敏感策略,并且用户可以通过继承 RoundRibbonRule 来实现自定义负载均衡策略,对Spring Cloud Ribbon负载均衡策略相关知识感兴趣的朋友一起看看吧
    2022-03-03
  • 浅谈spring容器中bean的初始化

    浅谈spring容器中bean的初始化

    下面小编就为大家带来一篇浅谈spring容器中bean的初始化。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-06-06
  • MyBatis配置文件元素示例详解

    MyBatis配置文件元素示例详解

    在MyBatis框架的核心配置文件中,<configuration>元素是配置文件的根元素,其他元素都要在<contiguration>元素内配置,这篇文章主要介绍了MyBatis配置文件元素,需要的朋友可以参考下
    2023-06-06
  • 使用ByteArrayOutputStream写入字符串方式

    使用ByteArrayOutputStream写入字符串方式

    这篇文章主要介绍了使用ByteArrayOutputStream写入字符串方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • java解析xml汇总_动力节点Java学院整理

    java解析xml汇总_动力节点Java学院整理

    这篇文章主要介绍了java解析xml汇总_动力节点Java学院整理的相关资料,需要的朋友可以参考下
    2017-07-07

最新评论