浅谈一下Java的线程并发
谈到并发,必会涉及操作系统中的线程概念,线程是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可以理解成同步屏障
场景:让一 组线程到达一个屏障(也可以叫同步点)时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,所有被屏障拦截的线程才会继续运行。
到此这篇关于浅谈一下Java的线程并发的文章就介绍到这了,更多相关Java线程并发内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)