多案例理解Object的wait,notify,notifyAll与Thread的sleep,yield,join等方法

简介: 多案例理解Object的wait,notify,notifyAll与Thread的sleep,yield,join等方法


1. wait,notify,notifyAll方法详解

1.1 wait-notify用法

  • 我们创建两个线程类,用一个object对象加锁,然后一个线程调用object.wati(),另一个调用object.notify(),且wait先执行。
  • 先看一段代码和结果
/**
 * wait和notify的基本用法
 * 1. 代码的执行顺序
 * 2. wait释放锁
 *
 * @author yiren
 */
public class Wait {
    private final static Object object = new Object();
    static class ThreadOne extends Thread {
        @Override
        public void run() {
            synchronized (object) {
                try {
                    System.out.println(Thread.currentThread().getName() + " in run before wait");
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " in run after wait");
            }
        }
    }
    static class ThreadTwo extends Thread {
        @Override
        public void run() {
            synchronized (object) {
                System.out.println(Thread.currentThread().getName() + " in run before notify");
                object.notify();
                System.out.println(Thread.currentThread().getName() + " in run after notify");
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        ThreadOne threadOne = new ThreadOne();
        ThreadTwo threadTwo = new ThreadTwo();
        threadOne.start();
        Thread.sleep(100);
        threadTwo.start();
    }
}
复制代码
Thread-0 in run before wait
Thread-1 in run before notify
Thread-1 in run after notify
Thread-0 in run after wait
Process finished with exit code 0
复制代码
  • 执行顺序如上结果,执行解释如下
  • Thread-0先进入执行,然后wait()进入等待唤醒的WAITING状态,并释放锁
  • Thread-1后进入执行,发现加锁了,然后等待Thread-0释放锁过后调用notify()通知Thread-0不用等了,不过此时由于Thread-1持有了object的锁,所以Thread-1先执行完毕后释放锁,然后Thread-0再拿到锁,把wait()后面的代码执行完毕。

1.2 wait-notifyAll 用法

  • 创建三个线程,两个线程wait,然后用第三个线程调用notifyAll唤醒
  • 代码和即如果如下
/**
 * 三个线程 2个被wait阻塞,另一个来唤醒他们
 *
 * @author yiren
 */
public class WaitNotifyAll implements Runnable {
    private static final Object objectOne = new Object();
    @Override
    public void run() {
        synchronized (objectOne) {
            Thread currentThread = Thread.currentThread();
            System.out.println(currentThread.getName() + " in run before wait, state is " + currentThread.getState());
            try {
                objectOne.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(currentThread.getName() + " in run after wait, state is " + currentThread.getState());
        }
    }
    public static void main(String[] args) throws InterruptedException {
        WaitNotifyAll waitNotifyAll = new WaitNotifyAll();
        Thread threadOne = new Thread(waitNotifyAll,"thread-one");
        Thread threadTwo = new Thread(waitNotifyAll,"thread-two");
        Thread threadThree = new Thread(() -> {
            synchronized (objectOne) {
                Thread currentThread = Thread.currentThread();
                System.out.println(currentThread.getName() + " in run before notifyAll, state is " + currentThread.getState());
                objectOne.notifyAll();
                System.out.println(currentThread.getName() + " in run after notifyAll, state is " + currentThread.getState());
            }
        }, "thread-three");
        threadOne.start();
        threadTwo.start();
        Thread.sleep(200);
        threadThree.start();
    }
}
复制代码
thread-one in run before wait, state is RUNNABLE
thread-two in run before wait, state is RUNNABLE
thread-three in run before notifyAll, state is RUNNABLE
thread-three in run after notifyAll, state is RUNNABLE
thread-two in run after wait, state is RUNNABLE
thread-one in run after wait, state is RUNNABLE
Process finished with exit code 0
复制代码
  • 线程1和2分别先后进入到WAITING状态后释放锁,
  • 线程3进入run方法后调用notifyAll唤醒,执行完毕run方法 释放锁,线程1和2抢占锁然后执行wait方法后面的代码。

1.3 wait释放锁

  • 我们在使用wait的时候,它只会释放它的那把锁,代码入下:
/**
 * 证明wait 只释放当前的那把锁
 *
 * @author yiren
 */
public class WaitNotifyReleaseOwnMonitor {
    private static final Object objectOne = new Object();
    private static final Object objectTwo = new Object();
    public static void main(String[] args) throws InterruptedException {
        Thread threadOne = new Thread(() -> {
            synchronized (objectOne) {
                System.out.println(Thread.currentThread().getName() + " got objectOne lock ");
                synchronized (objectTwo) {
                    System.out.println(Thread.currentThread().getName() + " got objectTwo lock ");
                    try {
                        System.out.println(Thread.currentThread().getName() + " release objectOne lock ");
                        objectOne.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        Thread threadTwo = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (objectOne) {
                System.out.println(Thread.currentThread().getName() + " got lock objectOne");
                synchronized (objectTwo) {
                    System.out.println(Thread.currentThread().getName() + " got lock objectTwo");
                }
            }
        });
        threadOne.start();
        threadTwo.start();
    }
}
复制代码
Thread-0 got objectOne lock 
Thread-0 got objectTwo lock 
Thread-0 release objectOne lock 
Thread-1 got lock objectOne
复制代码
  • 注意上面的运行并没有介绍。因为两个线程都还没有执行完毕。

1.4 wait、notify、notifyAll特点和性质

  • 使用时必须先拥有monitor,也就是获取到这个对象的锁
  • notify只唤醒一个,取决于JVM。notifyAll则是唤醒全部。
  • 都是数据Object的对象的方法,且都是final修饰的native方法。
  • 类似功能的有一个Condition对象
  • 如果线程同时持有多把锁一定要注意释放顺序,不然容易产生死锁。

1.5 生产者消费者模式实现

/**
 * 用wait notify实现生产者消费者模式
 * @author yiren
 */
public class ProducerConsumer {
    public static void main(String[] args) {
        EventStorage storage = new EventStorage();
        Thread producerThread = new Thread(new Producer(storage));
        Thread consumerThread = new Thread(new Consumer(storage));
        producerThread.start();
        consumerThread.start();
    }
    private static class Producer implements Runnable{
        EventStorage storage;
        public Producer(EventStorage storage) {
            this.storage = storage;
        }
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                storage.put();
            }
        }
    }
    private static class Consumer implements Runnable{
        EventStorage storage;
        public Consumer(EventStorage storage) {
            this.storage = storage;
        }
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                storage.take();
            }
        }
    }
    private static class EventStorage {
        private int maxSize;
        private LinkedList<LocalDateTime> storage;
        public EventStorage() {
            maxSize = 10;
            storage = new LinkedList<>();
        }
        public synchronized void put() {
            while (storage.size() == maxSize) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            storage.add(LocalDateTime.now());
            System.out.println("storage has " + storage.size() + " product(s).");
            notify();
        }
        public synchronized void take() {
            while (storage.size() == 0) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("get date " + storage.poll() + ", storage has " + storage.size() + " product(s).");
            notify();
        }
    }
}
复制代码
storage has 1 product(s).
storage has 2 product(s).
storage has 3 product(s).
storage has 4 product(s).
storage has 5 product(s).
storage has 6 product(s).
storage has 7 product(s).
storage has 8 product(s).
storage has 9 product(s).
storage has 10 product(s).
get date 2020-02-11T15:46:43.554, storage has 9 product(s).
get date 2020-02-11T15:46:43.554, storage has 8 product(s).
get date 2020-02-11T15:46:43.554, storage has 7 product(s).
get date 2020-02-11T15:46:43.554, storage has 6 product(s).
get date 2020-02-11T15:46:43.554, storage has 5 product(s).
get date 2020-02-11T15:46:43.554, storage has 4 product(s).
get date 2020-02-11T15:46:43.554, storage has 3 product(s).
get date 2020-02-11T15:46:43.554, storage has 2 product(s).
get date 2020-02-11T15:46:43.554, storage has 1 product(s).
get date 2020-02-11T15:46:43.555, storage has 0 product(s).
storage has 1 product(s).
storage has 2 product(s).
storage has 3 product(s).
storage has 4 product(s).
get date 2020-02-11T15:46:43.555, storage has 3 product(s).
get date 2020-02-11T15:46:43.555, storage has 2 product(s).
get date 2020-02-11T15:46:43.555, storage has 1 product(s).
get date 2020-02-11T15:46:43.555, storage has 0 product(s).
复制代码

1.6 常见面试问题

  • 两个线程交替打印0-100的奇偶数
  1. 用synchronized来实现
/**
 * 两个线程交替打印0-100
 * @author yiren
 */
public class OddEvenBySync {
    /*
     两个线程
        1. 一个处理偶数(Even),另一个处理奇数(Odd) 用位运算来实现判断
        2. 用synchronized 来实现
     */
    private static volatile int count = 0;
    private static final Object lock = new Object();
    public static void main(String[] args) {
        Thread threadEven = new Thread(() -> {
            while (count < 100) {
                synchronized (lock) {
                    // if (count % 2 == 0) {
                    if (0 == (count & 1)) {
                        System.out.println(Thread.currentThread().getName() + ": " + count++);
                    }
                }
            }
        }, "thread-even");
        Thread threadOdd = new Thread(() -> {
            while (count < 100) {
                synchronized (lock) {
                    // if (count % 2 == 0) {
                    if (1 == (count & 1)) {
                        System.out.println(Thread.currentThread().getName() + ": " + count++);
                    }
                }
            }
        }, "thread-odd");
        threadEven.start();
        threadOdd.start();
    }
}
复制代码
  1. 用wait-notify实现
/**
 * 使用wait-notify 实现奇偶打印
 * @author yiren
 */
public class OddEvenByWaitNotify {
    private static final Object lock = new Object();
    private static int count = 0;
    private static final int MAX_COUNT = 100;
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (count <= MAX_COUNT ) {
                    synchronized (lock) {
                        try {
                            System.out.println(Thread.currentThread().getName() + ": " + count++);
                            lock.notify();
                            // 如果任务还没结束 就让出锁 自己休眠
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
    }
}
复制代码
  • 手写生产者消费者设计模式 (前面有代码)
  • 为什么wait()需要在同步代码块中实现,而sleep不需要
  1. wait设计是针对多个线程的,如果多个线程运行的时候,在执行wait前就切换到了另外一个线程,恰好把notify执行掉了,那么就会形成死锁。
  2. 而sleep则是针对单个线程本身,不涉及到其他线程。
  • 为什么线程通信的方法wait(),notify()和notifyAll()被定义在Object类里面?而Sleep定义在Thread类里面?
  1. wait(),notify(),notifyAll()属于锁级别的操作,而锁一般是针对某个对象的,所以就定义在了Object中。每一个对象,在对象头中,都是有几位来表示当前锁的状态的,所以这个锁是绑定到某个对象上面,而并不是线程中。
  2. 如果把这些方法放在了Thread中,那么如果一个线程中持有了多把锁,就没有办法灵活的实现这样的多锁逻辑,也会增加编程难度。
  • wait()方法属于Object对象,那如果调用Thread.wait方法会怎样?
  • 对于Thread类特别特殊,因为在JVM中,线程在退出的现实中,它会自己去执行notify,这样会使我们设计的程序受到干扰。
  • 如何选择用notify和notifyAll
  • 主要考虑是我们需要唤醒的是单个线程还是多个线程
  • notifyAll之后所有的线程都会再次抢夺锁,如果某线程抢夺锁失败怎么办?
  • notifyAll线程执行完同步块中代码后,其他线程会同时竞争这把锁,只有一个线程会竞争成功,其他线程会进入到WAITING状态,等待竞争成功的这个线程执行结束再次竞争锁
  • 能不能用suspend()和resume()来阻塞线程?为什么?
  • Java官方是不推荐使用suspend来阻塞线程的,并且两个方法以及注明了过时,推荐使用wait-notify来实现

2. Sleep方法详解

  • 让线程在预期的时间执行,其他事件不要占用CPU资源
  • wait()会释放锁,但是sleep()方法不释放锁,包括synchronizedlock

2.1 sleep不释放锁

  1. synchronized
/**
 * sleep不释放锁
 * @author yiren
 */
public class SleepDontReleaseMonitor {
    public static void main(String[] args) {
        final Object object = new Object();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                synchronized (object) {
                    System.out.println(Thread.currentThread().getName() + " into synchronized !");
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " out to synchronized !");
                }
            }
        };
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
    }
}
复制代码
Thread-0 into synchronized !
Thread-0 out to synchronized !
Thread-1 into synchronized !
Thread-1 out to synchronized !
Process finished with exit code 0
复制代码
  1. Lock
public class SleepDontReleaseLock {
    private static final Lock LOCK = new ReentrantLock();
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                LOCK.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " into LOCK !");
                    Thread.sleep(3000);
                    System.out.println(Thread.currentThread().getName() + " out to LOCK !");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    LOCK.unlock();
                }
            }
        };
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
    }
}
复制代码
Thread-0 into LOCK !
Thread-0 out to LOCK !
Thread-1 into LOCK !
Thread-1 out to LOCK !
Process finished with exit code 0
复制代码

2.2 响应中断

  • 在调用时,会抛出InterruptedException,并且清除中断状态
/**
 * sleep响应中断案例
 * Thread.sleep()
 * TimeUnit.SECONDS.sleep()
 *
 * @author yiren
 */
public class SleepInterrupted {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + ": " + LocalDateTime.now());
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + ": was interrupted!");
                }
            }
        });
        thread.start();
        Thread.sleep(3500);
        thread.interrupt();
    }
}
复制代码
  • sleep(time)可以通过TimeUnit.时间单位.sleep(time)调用;此方法优于Thread.sleep(time)我们可以看下它的源码,它做了一个大于零的判断,以免传入负数,而Thread.sleep(time)中如果传入负数则会报IllegalArgumentException错误。
public void sleep(long timeout) throws InterruptedException {
        if (timeout > 0) {
            long ms = toMillis(timeout);
            int ns = excessNanos(timeout, ms);
            Thread.sleep(ms, ns);
        }
    }
复制代码

2.3 一句话总结

  • sleep(time)方法可以让线程进入到WAITING状态,并停止占用CPU资源,但是不释放锁,直到规定事件后再执行,休眠期间如果被中断,会抛出异常并清除中断状态。

2.4 常见面试问题

  • wait/notify、sleep异同
  • 方法属于哪个对象?线程状态怎么切换。
  • 相同:都进入阻塞,都响应中断
  • 不同:wait/notify需要同步块,sleep不需要;wait释放锁,sleep不释放;wait可不指定时间,sleep必须指定;所属类不同

3. join方法详解

3.1 作用及用法

  • 作用:新线程加入,所以要等待它执行完再出发
  • 用法:main等待thread1、thread2等线程执行完毕
  1. 普通用法
/**
 * 普通用法
 * @author yiren
 */
public class JoinSimple {
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " was finished!");
        };
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
        System.out.println("start to wait child threads.");
        thread1.join();
        thread2.join();
        System.out.println("all threads run completed!");
    }
}
复制代码
start to wait child threads.
Thread-0 was finished!
Thread-1 was finished!
all threads run completed!
Process finished with exit code 0
复制代码
  • 如果两个线程不join的话就会先打印最后一句话。
  1. 中断
  • thread.join()响应的中断是执行join方法的这个线程的中断 而不是thread,就如下方代码,中断的是主线程。
/**
 * 响应中断
 * @author yiren
 */
public class JoinInterrupt {
    public static void main(String[] args) {
        final Thread mainThread = Thread.currentThread();
        Runnable runnable = () -> {
            try {
                mainThread.interrupt();
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " was finished!");
        };
        Thread thread1 = new Thread(runnable);
        thread1.start();
        System.out.println("start to wait child thread.");
        try {
            thread1.join();
        } catch (InterruptedException e) {
            // 实际是主线程中断
            System.out.println(Thread.currentThread().getName() + " was interrupted!");
            e.printStackTrace();
        }
    }
}
复制代码
start to wait child thread.
main was interrupted!
java.lang.InterruptedException
  at java.lang.Object.wait(Native Method)
  at java.lang.Thread.join(Thread.java:1252)
  at java.lang.Thread.join(Thread.java:1326)
  at com.imyiren.concurrency.thread.method.JoinInterrupt.main(JoinInterrupt.java:25)
Thread-0 was finished!
Process finished with exit code 0
复制代码
  1. join期间线程状态
/**
 * join发生后 主线程的状态
 * @author yiren
 */
public class JoinState {
    public static void main(String[] args) {
        Thread mainThread = Thread.currentThread();
        Thread thread = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println("main thread state: " + mainThread.getState());
                System.out.println(Thread.currentThread().getName() + " finished");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();
        try {
            System.out.println("waiting child thread");
            thread.join();
            System.out.println("completed child thread");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
复制代码
waiting child thread
main thread state: WAITING
Thread-0 finished
completed child thread
Process finished with exit code 0
复制代码

3.2 join源码分析

public final void join() throws InterruptedException {
        join(0);
    }
    
    public final synchronized void join(long millis) throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }
        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }
复制代码
- `join(0)`是代表无限期等待
- 它的根本方法就是调用的`wait(time)`
- 但是没有notify?其实是JVM的Thread执行完毕会自动执行一次notifyAll。
- 既然知道它是通过wait-notify实现的,那么我们可以写一下等价的代码:
复制代码
/**
 * 自己实现 等价代码
 * @author yiren
 */
public class JoinImplements {
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " was finished!");
        };
        Thread thread1 = new Thread(runnable);
        thread1.start();
        System.out.println("start to wait child threads.");
        // thread1.join(); // 等价于下方代码
        synchronized (thread1) {
            thread1.wait();
        }
        System.out.println("all threads run completed!");
    }
}
复制代码

3.3 常见面试题

  • 在join期间线程会处于那种状态?
  • WAITING

4. yield方法详解

  • 释放当前CPU占用,状态依旧是RUNNABLE
  • JVM不保证遵循yield,如CPU资源不紧张,极端点没有线程使用,即使调用yield也有可能不释放CPU资源
  • 与sleep的区别:是否可以随时再次被调度

5. Thread.currentThread()方法

  • 主要是返回当前线程的引用。
/**
 * 打印main thread-0 thread-1
 * @author yiren
 */
public class CurrentThread {
    public static void main(String[] args) {
        Runnable runnable = () -> System.out.println(Thread.currentThread().getName());
        // 主线程直接调用函数
        runnable.run();
        new Thread(runnable).start();
        new Thread(runnable).start();
    }
}
复制代码

6. start run 方法 和 stop suspend resume 方法

7. 面试常见问题

  • 为什么线程通信的方法wait(),notify()和notifyAl()被定义在Object类里面?而sleep却定义在Thread类中
  • 用三种方法实现生产者模式
  • join和sleep和wait期间线程的状态分别是什么?为什么?


目录
相关文章
|
25天前
|
存储 监控 开发工具
对象存储OSS产品常见问题之python sdk中的append_object方法支持追加上传xls文件如何解决
对象存储OSS是基于互联网的数据存储服务模式,让用户可以安全、可靠地存储大量非结构化数据,如图片、音频、视频、文档等任意类型文件,并通过简单的基于HTTP/HTTPS协议的RESTful API接口进行访问和管理。本帖梳理了用户在实际使用中可能遇到的各种常见问题,涵盖了基础操作、性能优化、安全设置、费用管理、数据备份与恢复、跨区域同步、API接口调用等多个方面。
52 9
|
2月前
|
JavaScript
JS之Object.defineProperty方法
JS之Object.defineProperty方法
|
4月前
|
存储 JavaScript 前端开发
【JavaScript】<面向对象Object>函数方法&对象创建&原型对象&作用域解析
【1月更文挑战第17天】【JavaScript】<面向对象Object>函数方法&对象创建&原型对象&作用域解析
|
7月前
|
Java
【面试题精讲】Object类的常见方法有哪些?
【面试题精讲】Object类的常见方法有哪些?
|
8月前
|
Java API 开发工具
Java之API详解之Object类的详细解析(下)
Java之API详解之Object类的详细解析(下)
40 0
|
3天前
|
C#
c# 所有类的最终基类:Object
c# 所有类的最终基类:Object
5 0
|
18天前
|
XML JSON Java
作为所有类的顶层父类,没想到Object的魔力如此之大!
在上一篇博文中我们提到了Java面向对象的四大特性,其中谈及“抽象”特性时做了一个引子,引出今天的主人公Object,作为所有类的顶级父类,Object被视为是James.Gosling的哲学思考,它高度概括了事务的自然与社会行为。
53 13
|
18天前
|
存储 Java 开发者
Java Object类
Java Object类
14 0
|
2月前
|
存储 设计模式 Python
Python中的类(Class)和对象(Object)
Python中的类(Class)和对象(Object)
32 0
|
7月前
|
Java
Java常用类--------Object类
Java常用类--------Object类