亲宝软件园·资讯

展开

Java线程并发

ldcaws 人气:0

谈到并发,必会涉及操作系统中的线程概念,线程是CPU分配的最小单位,windows系统是抢占式的,linux是轮询式的,都需要获取CPU资源。
并行:同一时刻,两个线程都在执行。
并发:同一时刻,只有一个线程执行,但是一个时间段内,两个线程都执行了。
java中创建线程的三种方式,分别为集成Thread类、实现Runnable接口,实现Callable接口。

在这里插入图片描述

示例

public class ThreadTest {

    public static class MyThread extends Thread {

        @Override
        public void run() {
            System.out.println("This is a thread");
        }
    }

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
    }
}
public class RunnableTest implements Runnable {

    @Override
    public void run() {
        System.out.println("Runnable!");
    }

    public static void main(String[] args) {
        RunnableTest runnableTest = new RunnableTest();
        new Thread(runnableTest).start();
    }
}
public class CallableTest implements Callable<String> {

    @Override
    public String call() throws Exception {
        return "Callable!";
    }

    public static void main(String[] args) {
        FutureTask<String> futureTask = new FutureTask<>(new CallableTest());
        new Thread(futureTask).start();
        try {
            String result = futureTask.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

CountDownLatch理解成倒计数器
场景:玩的王者荣耀,创建大乔、兰陵王、安其拉、哪吒和铠等五个玩家,主线程必须在他们都完成确认后,才可以继续运行。

public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(5);

        Thread DaQiao = new Thread(countDownLatch::countDown);
        Thread LanLingWang = new Thread(countDownLatch::countDown);
        Thread AnQiLa = new Thread(countDownLatch::countDown);
        Thread NeZha = new Thread(countDownLatch::countDown);
        Thread Kai = new Thread(() -> {
            try {
                // 稍等,上个卫生间,马上到...
                Thread.sleep(1500);
                countDownLatch.countDown();
            } catch (InterruptedException ignored) {}
        });

        DaQiao.start();
        LanLingWang.start();
        AnQiLa.start();
        NeZha.start();
        Kai.start();
        countDownLatch.await();
        System.out.println("所有玩家已经就位!");
    }

CyclicBarrier可以理解成同步屏障
场景:让一 组线程到达一个屏障(也可以叫同步点)时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,所有被屏障拦截的线程才会继续运行。

加载全部内容

相关教程
猜你喜欢
用户评论