sleep()、wait()、join()、yield()之间的区别

本文详细介绍了Java中线程的几个关键方法:sleep()用于让当前线程暂停指定时间,不释放对象锁;wait()使线程释放锁并进入等待队列,需其他线程唤醒;join()等待其他线程结束再执行;yield()则让当前线程让出CPU,但不释放锁。
摘要由CSDN通过智能技术生成
  1. sleep()是Thread类的静态方法,它可以让当前线程暂停执行指定的时间,不会释放对象锁,也不会进入等待队列或锁池,只是让出CPU资源给其他线程。sleep()方法可以被其他线程的interrupt()方法打断,抛出InterruptedException异常。
// sleep()示例
public class SleepDemo {
    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable(), "t1");
        Thread t2 = new Thread(new MyRunnable(), "t2");
        t1.start();
        t2.start();
    }
}

class MyRunnable implements Runnable {
    @Override
    public void run() {
        synchronized (MyRunnable.class) {
            System.out.println(Thread.currentThread().getName() + " is running");
            try {
                // 让当前线程睡眠3秒
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " is finished");
        }
    }
}
// 输出结果:
t1 is running
t1 is finished
t2 is running
t2 is finished
  1. wait()是Object类的方法,它可以让当前线程释放对象锁,并进入该对象的等待队列,等待其他线程调用notify()或notifyAll()方法来唤醒。wait()方法必须在同步代码块或同步方法中调用,否则会抛出IllegalMonitorStateException异常。wait()方法也可以被其他线程的interrupt()方法打断,抛出InterruptedException异常。
// wait()示例
public class WaitDemo {
    public static void main(String[] args) {
        Object lock = new Object();
        Thread t1 = new Thread(new WaitRunnable(lock), "t1");
        Thread t2 = new Thread(new NotifyRunnable(lock), "t2");
        t1.start();
        t2.start();
    }
}

class WaitRunnable implements Runnable {
    private Object lock;

    public WaitRunnable(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        synchronized (lock) {
            System.out.println(Thread.currentThread().getName() + " is running");
            try {
                // 让当前线程释放锁并等待
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " is resumed");
        }
    }
}

class NotifyRunnable implements Runnable {
    private Object lock;

    public NotifyRunnable(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        synchronized (lock) {
            System.out.println(Thread.currentThread().getName() + " is running");
            // 唤醒在lock上等待的一个线程
            lock.notify();
            System.out.println(Thread.currentThread().getName() + " is finished");
        }
    }
}
// 输出结果
t1 is running
t2 is running
t2 is finished
t1 is resumed
  1. join()是Thread类的实例方法,它可以让当前线程等待另一个线程执行完毕后再继续执行。join()方法实际上是调用了wait()方法,因此也会释放对象锁,并进入等待队列。join()方法可以指定等待的时间,如果超过了时间还没有被唤醒,就会自动返回。join()方法也可以被其他线程的interrupt()方法打断,抛出InterruptedException异常。
// join()示例
// 创建一个线程B
Thread threadB = new Thread(new Runnable() {
    @Override
    public void run() {
        // 模拟耗时操作
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread B is finished.");
    }
});

// 创建一个线程A
Thread threadA = new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("Thread A is waiting for Thread B.");
        // 调用线程B的join()方法
        try {
            threadB.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread A is resumed.");
    }
});

// 启动两个线程
threadB.start();
threadA.start();

// 输出结果:
Thread A is waiting for Thread B.
Thread B is finished.
Thread A is resumed.

  1. yield()是Thread类的静态方法,它可以让当前线程主动放弃CPU资源,让具有相同优先级的其他线程有机会执行。yield()方法不会释放对象锁,也不会进入等待队列或锁池,只是回到就绪状态,等待CPU调度。yield()方法不会抛出任何异常。
// yield()示例
public class YieldDemo {
    public static void main(String[] args) {
        Thread t1 = new Thread(new YieldRunnable(), "t1");
        Thread t2 = new Thread(new YieldRunnable(), "t2");
        t1.start();
        t2.start();
    }
}

class YieldRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + " is running");
            // 让当前线程让出CPU资源,让其他同优先级的线程有机会执行
            Thread.yield();
        }
    }
}
// 输出结果(可能不同):
t1 is running
t2 is running
t1 is running
t2 is running
t1 is running
t2 is running
t1 is running
t2 is running
t1 is running
t2 is running
t1 is running
t2 is running
t1 is running
t2 is running
t1 is running
t2 is running
t1 is running
t2 is running
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值