并发编程

三、线程的挂起与唤醒

2020-08-31  本文已影响0人  liyc712

线程的挂起与唤醒

一、使用object

public class WaitDemo implements Runnable {

    private static Object waitObj = new Object();

    @Override
    public void run() {
        //持有资源
        synchronized (waitObj) {
            System.out.println(Thread.currentThread().getName()+"占用资源");
            try {
                waitObj.wait();// 调用wait会释放资源
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName()+"释放资源");
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new WaitDemo(),"对比线程");
        thread.start();

        Thread thread2 = new Thread(new WaitDemo(),"对比线程2");
        thread2.start();
        Thread.sleep(3000L);

        synchronized (waitObj) {
            waitObj.notify();
        }

    }
}

二、被废弃的方法

/**
 * 挂起操作的Demo
 */
public class SuspendDemo implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"执行run方法,准备调用suspend方法");
        //挂起线程
        Thread.currentThread().suspend();// 挂起线程不会释放资源,容易死锁
        System.out.println(Thread.currentThread().getName()+"执行run方法,调用suspend方法结束");

    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new SuspendDemo());
        thread.start();
        Thread.sleep(3000L);
        //对线程进行唤醒操作
        thread.resume();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读