线程间通信示例

/**
     * 两个线程同时执行
     */
    private static void demo1(){
        Thread A = new Thread(new Runnable() {
            @Override
            public void run() {
                printStr("A");
            }
        });
        Thread B = new Thread(new Runnable() {
            @Override
            public void run() {
                printStr("B");
            }
        });
        A.start();
        B.start();
    }

    /**
     * A打印完成后B再打印
     */
    private static void demo2(){
        Thread A = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("A开始打印...");
                printStr("A");
            }
        });
        Thread B = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("B等待A打印完成...");
                try {
                    A.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                printStr("B");
            }
        });
        A.start();
        B.start();
    }

    /**
     * A打印1后B打印123,然后A打印23
     */
    private static void demo3(){
        Object lock = new Object(); // 创建共享锁
        Thread A = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    System.out.println("A开始打印...");
                    System.out.println("A -> 1");
                    try {
                        System.out.println("A开始等待");
                        lock.wait(); // A交出锁的控制权,进入等待状态
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("A -> 2");
                    System.out.println("A -> 3");
                    System.out.println("A打印结束");
                }
            }
        });

        Thread B = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    System.out.println("B得到锁的控制权,开始打印...");
                    System.out.println("B -> 1");
                    System.out.println("B -> 2");
                    System.out.println("B -> 3");
                    System.out.println("B打印结束,通知A继续打印");
                    lock.notify(); // B唤醒A,A继续打印
                }
            }
        });

        // 注意:应优先让A拿到共享锁,如果B先于A拿到共享锁,则A线程将一直等待先去
        A.start();
        B.start();
    }

    /**
     * A,B,C,D四个线程,A,B,C同时执行,全部完成后D线程执行
     */
    private static void demo4() {
        CountDownLatch countDownLatch = new CountDownLatch(3); // 创建计数器
        Thread A = new Thread(new Runnable() {
            @Override
            public void run() {
                printStr("A");
                countDownLatch.countDown(); // 线程执行完成,计数器减1
            }
        });
        Thread B = new Thread(new Runnable() {
            @Override
            public void run() {
                printStr("B");
                countDownLatch.countDown(); // 线程执行完成,计数器减1
            }
        });
        Thread C = new Thread(new Runnable() {
            @Override
            public void run() {
                printStr("C");
                countDownLatch.countDown(); // 线程执行完成,计数器减1
            }
        });
        Thread D = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    countDownLatch.await(); // 计数器为0时线程开始执行
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                printStr("D");
            }
        });
        A.start();
        B.start();
        C.start();
        D.start();
    }

    /**
     * A,B,C全部准备好之后在一起执行
     */
    private static void demo5(){
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        Random random = new Random();
        Thread A = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int i = random.nextInt(4);
                    long time = (i + 1) * 1000L;
                    Thread.sleep(time);
                    System.out.println("A准备就绪,耗时:" + time + "秒,等待开始...");
                    cyclicBarrier.await(); // 等待其他线程准备就绪
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                long timeMillis = System.currentTimeMillis();
                System.out.println("A发车了...,当前时间:" + timeMillis);
            }
        });
        Thread B = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int i = random.nextInt(4);
                    long time = (i + 1) * 1000L;
                    Thread.sleep(time);
                    System.out.println("B准备就绪,耗时:" + time + "秒,等待开始...");
                    cyclicBarrier.await(); // 等待其他线程准备就绪
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                long timeMillis = System.currentTimeMillis();
                System.out.println("B发车了...,当前时间:" + timeMillis);
            }
        });
        Thread C = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int i = random.nextInt(4);
                    long time = (i + 1) * 1000L;
                    Thread.sleep(time);
                    System.out.println("C准备就绪,耗时:" + time + "秒,等待开始...");
                    cyclicBarrier.await(); // 等待其他线程准备就绪
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                long timeMillis = System.currentTimeMillis();
                System.out.println("C发车了...,当前时间:" + timeMillis);
            }
        });
        A.start();
        B.start();
        C.start();
    }

    /**
     * 主线程获取子线程返回的结果
     */
    private static void demo6(){
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int total = 0;
                System.out.println("子线程开始执行...");
                for (int i = 0; i <= 10; i++) {
                    total += i;
                }
                System.out.println("子线程执行完成,返回结果");
                return total;
            }
        };
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        new Thread(futureTask).start();

        System.out.println("主线程执行...");
        try {
            Integer integer = futureTask.get();
            System.out.println("主线程获得的子线程返回的结果为:" + integer);
            System.out.println("主线程执行完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private static void printStr(String threadName) {
        int i = 1;
        System.out.println(threadName + "开始打印...");
        while (i <= 3) {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(threadName + " -> " + i);
            i ++;
        }
        System.out.println(threadName + "打印结束");
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值