温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java多线程:如何实现线程协作

发布时间:2025-11-01 01:01:00 来源:亿速云 阅读:103 作者:小樊 栏目:编程语言

在Java中,线程协作可以通过以下几种方式实现:

  1. 使用wait()和notify()方法: 这两个方法用于线程间的协作,它们是Object类的成员方法。当一个线程调用某个对象的wait()方法时,该线程会释放该对象的锁并进入等待状态。当另一个线程调用同一个对象的notify()方法时,等待该对象的线程会被唤醒并重新获取锁。这样可以实现线程间的协作。

示例:

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

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                try {
                    System.out.println("Thread 1 waiting...");
                    lock.wait();
                    System.out.println("Thread 1 resumed.");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lock) {
                System.out.println("Thread 2 notifying...");
                lock.notify();
                System.out.println("Thread 2 finished.");
            }
        });

        t1.start();
        t2.start();
    }
}
  1. 使用join()方法: join()方法用于等待一个线程完成其任务。当一个线程调用另一个线程的join()方法时,当前线程会阻塞,直到被调用的线程完成任务。

示例:

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

        Thread t2 = new Thread(() -> {
            try {
                System.out.println("Thread 2 started.");
                t1.join();
                System.out.println("Thread 2 finished.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t1.start();
        t2.start();
    }
}
  1. 使用CountDownLatch类: CountDownLatch是一个同步辅助类,它允许一个或多个线程等待其他线程完成操作。通过使用CountDownLatch,可以实现线程间的协作。

示例:

import java.util.concurrent.CountDownLatch;

public class ThreadCooperation {
    public static void main(String[] args) {
        int numberOfThreads = 2;
        CountDownLatch latch = new CountDownLatch(numberOfThreads);

        Thread t1 = new Thread(() -> {
            System.out.println("Thread 1 started.");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread 1 finished.");
            latch.countDown();
        });

        Thread t2 = new Thread(() -> {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread 2 started.");
            System.out.println("Thread 2 finished.");
        });

        t1.start();
        t2.start();
    }
}
  1. 使用CyclicBarrier类: CyclicBarrier是一个同步辅助类,它允许一组线程互相等待,直到所有线程都准备好继续执行。通过使用CyclicBarrier,可以实现线程间的协作。

示例:

import java.util.concurrent.CyclicBarrier;

public class ThreadCooperation {
    public static void main(String[] args) {
        int numberOfThreads = 2;
        CyclicBarrier barrier = new CyclicBarrier(numberOfThreads, () -> {
            System.out.println("All threads are ready.");
        });

        Thread t1 = new Thread(() -> {
            System.out.println("Thread 1 started.");
            try {
                Thread.sleep(3000);
                barrier.await();
                System.out.println("Thread 1 finished.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            System.out.println("Thread 2 started.");
            try {
                barrier.await();
                System.out.println("Thread 2 finished.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        t1.start();
        t2.start();
    }
}

这些方法可以帮助您实现Java多线程间的协作。根据您的需求选择合适的方法。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手