java 线程间通信的几种实现方式

该文展示了三种Java实现多线程交替打印字符串的方法:1)使用wait/notify,2)利用LockSupport工具类,3)通过ReentrantLock和Condition。每种方法都确保了线程间的协作和同步,避免了竞态条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假设有一段字符串“1A2B3C4D”, 启动两个线程,线程交替打印字符串中的某个字符

方法一:使用wait、notify的方式实现

public class ThreadCommunication {

    public static String str = "1A2B3C4";
    public static Object monitor = new Object();
    public static boolean running = true;
    public static int sept = -1;

    public static void main(String[] args) {

        char[] chars = str.toCharArray();

        new Thread(() -> {
            while (true) {
                synchronized (monitor) {
                    if(running) {
                        int index = getIndex(chars.length);
                        System.out.print(Thread.currentThread().getName() + " : " );
                        System.out.println(chars[index]);
                        running = false;
                        SleepUtil.sleep(1);
                        monitor.notifyAll();
                    } else {
                        try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }

        }).start();

        new Thread(() -> {
            while (true) {
                synchronized (monitor) {
                    if(!running) {
                        int index = getIndex(chars.length);
                        System.out.print(Thread.currentThread().getName() + " : " );
                        System.out.println(chars[index]);
                        running = true;
                        SleepUtil.sleep(1);
                        monitor.notifyAll();
                    } else {

                        try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }

                    }

                }
            }
        }).start();
    }

    public static int getIndex(int size) {
        sept ++;
        if(sept == size) {
            sept = 0;
        }
        return sept;
    }


}

方法二:使用LockSupport工具类实现

import java.util.concurrent.locks.LockSupport;

public class ThreadCommunication2 {

    public static String str = "1A2B3C4";
    public static int sept = -1;

    public static Thread t1, t2;

    public static void main(String[] args) {
        char[] chars = str.toCharArray();

        t1 = new Thread(() -> {
            while (true) {
                int index = getIndex(chars.length);
                System.out.print(Thread.currentThread().getName() + " : " );
                System.out.println(chars[index]);
                SleepUtil.sleep(1);
                LockSupport.unpark(t2);
                LockSupport.park();
            }
        }, "T1");


        t2 = new Thread(() -> {
            while (true) {
                LockSupport.park();
                int index = getIndex(chars.length);
                System.out.print(Thread.currentThread().getName() + " : " );
                System.out.println(chars[index]);
                SleepUtil.sleep(1);
                LockSupport.unpark(t1);
            }
        }, "T2");

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

    public static int getIndex(int size) {
        sept ++;
        if(sept == size) {
            sept = 0;
        }
        return sept;
    }

}

方法三:使用ReentrantLock、Condition实现

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadCommunication3 {

    public static String str = "1A2B3C4";
    public static int sept = -1;

    public static ReentrantLock lock = new ReentrantLock();
    public static Condition h = lock.newCondition();
    public static Condition d = lock.newCondition();


    public static void h(char[] chars, int index) throws Exception {
       lock.lock();
       try {
           System.out.print(Thread.currentThread().getName() + " : " );
           System.out.println(chars[index]);
           SleepUtil.sleep(1);
           d.signal();
           h.await();
       } finally {
           lock.unlock();
       }
    }

    public static void d(char[] chars, int index) throws Exception {
        lock.lock();
        try {
            System.out.print(Thread.currentThread().getName() + " : " );
            System.out.println(chars[index]);
            SleepUtil.sleep(1);
            h.signal();
            d.await();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        char[] chars = str.toCharArray();

        new Thread(() -> {
            while (true) {
                int index = getIndex(chars.length);
                try {
                    h(chars, index);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }


        }).start();

        new Thread(() -> {
            while (true) {
                int index = getIndex(chars.length);
                try {
                    d(chars, index);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    public static int getIndex(int size) {
        sept ++;
        if(sept == size) {
            sept = 0;
        }
        return sept;
    }

}

以上三种方法,是目前我想到的。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

x_pengcheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值