Java

Java中join方法与wait方法的关系

小樊
83
2024-09-13 00:38:40
栏目: 编程语言

在Java中,join()wait()方法都用于线程间的通信和协作,但它们的用途和机制有所不同。

  1. join()方法: join()方法属于Thread类,用于等待一个线程完成(终止)后,再继续执行当前线程。当一个线程调用另一个线程的join()方法时,当前线程会被阻塞,直到被调用线程完成执行。这样可以确保被调用线程的结果被当前线程正确处理。join()方法可以用于实现线程之间的同步和顺序执行。

示例:

public class JoinExample {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            System.out.println("Thread 1 is running");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread 1 finished");
        });

        t1.start();
        t1.join(); // Main thread will wait for t1 to finish

        System.out.println("Main thread continues after t1 finished");
    }
}
  1. wait()方法: wait()方法属于Object类,用于让当前线程等待某个条件成立。当一个线程调用对象的wait()方法时,该线程会释放对象的锁并进入等待状态。当其他线程调用相同对象的notify()notifyAll()方法时,等待状态的线程将被唤醒。wait()方法通常与synchronized关键字一起使用,以实现线程间的同步和条件通知。

示例:

public class WaitNotifyExample {
    private final Object lock = new Object();

    public void producer() {
        synchronized (lock) {
            System.out.println("Producing data...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Data produced, notifying consumer");
            lock.notify(); // Notify the consumer thread
        }
    }

    public void consumer() {
        synchronized (lock) {
            while (true) {
                try {
                    lock.wait(); // Wait for data to be produced
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Consuming data...");
                break;
            }
        }
    }

    public static void main(String[] args) {
        WaitNotifyExample example = new WaitNotifyExample();

        Thread producerThread = new Thread(example::producer);
        Thread consumerThread = new Thread(example::consumer);

        consumerThread.start();
        producerThread.start();
    }
}

总结:

0
看了该问题的人还看了