Java实现多个线程一起并发执行

面试人员:用Java的多线程模拟一个赛马,马场上有10匹马,要求他们同时起跑

设计到的Java多线程技术:CountDownLatch或者CyclicBarrier

/**
 * <p>
 * <p>Title:testCountDownLatch.java</p >
 * <p>Description: </p >
 * <p>Date:2020/10/20 14:53</p >
 *
 * @author wsh
 * @version 1.0
 */
public class testCountDownLatch {
    CountDownLatch countDownLatch = new CountDownLatch(1);
    private  void runThread(){
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for(int i=0;i<10 ;i++){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        countDownLatch.await();
                        System.out.println("Thread:"+Thread.currentThread().getName()+",time: "+System.currentTimeMillis());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            });
        }
        countDownLatch.countDown();
    }

    public static void main(String[] args) {
        testCountDownLatch test = new testCountDownLatch();
        test.runThread();
    }
}

运行结果:

/**
 * <p>
 * <p>Title:CyclicBarrierTest.java</p >
 * <p>Description: 做到10个线程同时start</p >
 * <p>Date:2020/10/20 14:41</p >
 *
 * @author wsh
 * @version 1.0
 */
public class CyclicBarrierTest {

    /**
     * CyclicBarrier 适用再多线程相互等待,直到到达一个屏障点。并且CyclicBarrier是可重用的。
     */
    CyclicBarrier cyclicBarrier = new CyclicBarrier(10);

    private void runThread() {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            executorService.submit(createThread(i));
        }
    }

    private Thread createThread(int i) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    cyclicBarrier.await();
                    System.out.println("Thread:" + Thread.currentThread().getName() + "准备完毕,time:" + System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.setName("name" + i);
        return thread;
    }

    public static void main(String[] args) {
        CyclicBarrierTest test = new CyclicBarrierTest();
        test.runThread();
    }
}

运行结果:

  • 4
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中,可以通过以下几种方式实现线程并发: 1. 继承Thread类:创建一个新的类,并继承Thread类,重写run()方法,在run()方法中编写该线程执行逻辑。然后创建该类的实例,并调用start()方法启动线程。 ```java class MyThread extends Thread { public void run() { // 线程执行逻辑 } } public class Main { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); } } ``` 2. 实现Runnable接口:创建一个实现Runnable接口的类,实现其run()方法,在run()方法中编写该线程执行逻辑。然后创建该类的实例并传入Thread的构造函数中,最后调用start()方法启动线程。 ```java class MyRunnable implements Runnable { public void run() { // 线程执行逻辑 } } public class Main { public static void main(String[] args) { MyRunnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.start(); } } ``` 3. 使用Executor框架:Java提供了Executor框架来管理和控制线程执行。可以使用ThreadPoolExecutor或ScheduledThreadPoolExecutor来创建线程池,并通过submit()方法提交任务。 ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { Runnable worker = new MyRunnable(); executor.execute(worker); } executor.shutdown(); } } ``` 以上是Java实现线程并发的几种常见方式。根据具体的需求和场景,选择适合的方式来实现线程并发
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值