zoukankan      html  css  js  c++  java
  • 关于线程的synchronized,wait,sleep,notify的一段有趣的代码

    首先进入正题,来看代码:

    public class MultiThread {
    public static void main(String[] args) {

    new Thread (new Thread1()).start();
    try{
    Thread.sleep(10);
    }catch(InterruptedException e){
    e.printStackTrace();
    }
    new Thread(new Thread2()).start();
    }
    private static class Thread1 implements Runnable{
    public void run(){
    synchronized(MultiThread.class){
    System.out.println("enter Thread1...");
    System.out.println("Thread1 is waiting ");
    try{
    MultiThread.class.wait();
    }catch(InterruptedException e){
    e.printStackTrace();
    }
    System.out.println("thread1 is going on...");
    System.out.println("thread1 is being over!");
    }
    }
    }
    private static class Thread2 implements Runnable{
    public void run(){
    synchronized(MultiThread.class){
    System.out.println("enter Thread2...");
    System.out.println("Thread2 notify other thread can release wait....");
    MultiThread.class.notify();
    System.out.println("thread2 is sleeping 10 m");
    try{
    Thread.sleep(10);
    }catch(InterruptedException e){
    e.printStackTrace();
    }
    System.out.println("thread2 is going on...");
    System.out.println("thread2 is being over!");
    }
    }
    }
    }

    再来看结果:

    本代码。首先按照顺序运行,执行代码:

    但是继续往下执行的时候便遇到了wait方法,要知道,wait方法不仅会让出正在执行线程所用的cpu,还会将锁释放出去。而Thread1与Thread2同步,开始都有锁,但Thread1释放之后,自然而然的便会运行到Thread2了。所以便运行到了一下代码:

    接下来便遇到了notify方法,唤醒等待的线程,但是呢,它只是简单的唤醒,并不会给线程加锁,所以现在有锁的还是Thread2线程。所以继续往下执行。于是便到了一下代码处:

    等待睡眠时间过了以后,有执行以下代码:

    到此,Thread2执行完了,便释放掉锁,也就顺理成章的执行Thread1最后的部分:

     

    到此为止,程序运行结束!

  • 相关阅读:
    带横线圆圈标题
    锚点点击导航 跳转到相应位置,样式随之变化
    导航随滚动改变样式
    for循环中嵌套函数,执行顺序和结果该如何理解?
    mui 记录
    获取页面所有a标签href
    cookie记录横向滚动条位置
    Istio全景监控与拓扑
    Istio 流量治理功能原理与实战
    Cloud Native Weekly | KubeCon首登中国,华为云亮相KubeCon 2018,微软云服务又罢工
  • 原文地址:https://www.cnblogs.com/1987721594zy/p/7193600.html
Copyright © 2011-2022 走看看