多线程学习笔记--05线程间的通信(join方法的使用)
发布日期:2021-05-20 07:58:19 浏览次数:18 分类:精选文章

本文共 2900 字,大约阅读时间需要 9 分钟。

understand thread.join() and synchronized differences

Understanding join() and how it differs from synchronized is crucial for effective multithreading programming.

1. Functionality

  • join(): Waits for the thread to finish its execution. It releases the lock, allowing other threads to access synchronized resources after it. Uses wait() method which is interruptible.
  • synchronized: Controls access to a block of code by acquiring and releasing a lock. Ensures only one thread can execute the block at a time. Uses "object monitor" mechanism.

2. Example Use Cases

  • Using join():

    package com.wx.threadlearn2;public class MyThread extends Thread {    @Override    public void run() {        System.out.println("123");        Thread.sleep(5000);    }}public class Test1 {    public static void main(String[] args) {        try {            MyThread myThread = new MyThread();            myThread.start();            myThread.join();            System.out.println("等myThread执行完再执行");        } catch (Exception e) {            e.printStackTrace();        }    }}
  • Using synchronized:

    public class MyService {    // Synchronized code block    public synchronized void doSomething() {        // Only one thread can execute this method at a time    }}public class TestSync {    public static void main(String[] args) {        MyService obj = new MyService();        // Only one thread can execute doSomething() at a time        Runnable task1 = () -> obj.doSomething();        Runnable task2 = () -> obj.doSomething();        Thread thread1 = new Thread(task1);        Thread thread2 = new Thread(task2);        thread1.start();        thread2.start();    }}

3. Differences

  • Mechanism:

    • join() uses wait() which is interruptible.
    • synchronized uses "object monitor" which acquires and releases locks.
  • 效果:

    • join() allows current thread to wait for finishing thread to complete.
    • synchronized ensures only one thread can execute code at a time by controlling access to a block.
  • 同步方式:

    • join() 不是通过同步块,而是通过等待线程的完成。
    • synchronized 使用同步块确保以一种互斥的方式执行代码。

4. Advantages and Considerations

  • join() is interruptible, meaning if current thread is interrupted while waiting, it will throw InterruptedException.
  • synchronized is not interruptible; it always completes waiting for the lock to be released.

5. Improved Code with join()

  • 使用join()后面的代码可能更早地执行,但需要注意可能的中断情况。
  • 在实现join()时,需要处理InterruptedException异常。

6. Correct Usage

  • Always wrap join() in a try-catch block to handle InterruptedException.
  • 确保在使用多线程时正确使用synchronized 以防止竞争条件和死锁。

7. Summary

  • join() and synchronized both contribute to thread synchronization but through different mechanisms.

  • join() allows thread A to wait for thread B to complete, making thread A wait and then proceed.

  • synchronized ensures thread safety in code execution by controlling access through locks.

  • Understanding the distinction is key to writing efficient, correct, and scalable multithreaded programs.

上一篇:springboot--02(ajax请求json数据动态绑定到echars)
下一篇:hadoop04--(mapreduce增强)

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年04月28日 03时51分39秒