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最后的部分:

     

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

  • 相关阅读:
    线段树练习两题
    DP+单调队列 codevs 1748 瑰丽华尔兹(还不是很懂具体的代码实现)
    线段树和树状数组问题补充
    一些常见的优化:读入优化,滚动数组
    单调队列应用--BZOJ 3831 Little Bird
    单调队列练习之广告印刷
    详解--单调队列 经典滑动窗口问题
    数据结构--栈 codevs 1107 等价表达式
    离散化+线段树 POJ 3277 City Horizon
    求次短路 codevs 1269 匈牙利游戏
  • 原文地址:https://www.cnblogs.com/1987721594zy/p/7193600.html
Copyright © 2011-2022 走看看