這篇文章主要講解了“多線程執(zhí)行的過(guò)程”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“多線程執(zhí)行的過(guò)程”吧!
創(chuàng)新互聯(lián)建站堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站制作、網(wǎng)站設(shè)計(jì)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的儀隴網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
1、主線程等待子線程執(zhí)行完成后再執(zhí)行——Thread.join()
Vectorvector = new Vector<>(10); for (int i = 0; i < 10; i++) { MyThread myThread = new MyThread("id" + i, "name" + i, roles); Thread t = new Thread(myThread); vector.add(t); t.start(); } for (Thread thread : vector) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } }
2、Java多線程--讓主線程等待子線程執(zhí)行完畢(CountDownLatch類)
Runable接口實(shí)現(xiàn)類
import com.winning.jcfw.core.util.SpringUtil; import com.winning.jcfw.empi.dao.DaGrJbxxDao; import com.winning.jcfw.empi.entity.PatientEntity; import com.winning.jcfw.empi.service.RegisterEmpiService; import com.winning.jcfw.empi.service.impl.RegisterEmpiSerImpl; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import java.util.List; import java.util.concurrent.CountDownLatch; /** * @ClassName DaGrJbxxEmpiRunnable * @Description 公衛(wèi)表 DA_GR_JBXX 線程執(zhí)行單條生成EMPI * @Author WJX * @Date 2019/10/25 17:45 **/ @Slf4j public class DaGrJbxxEmpiRunnable implements Runnable{ private RegisterEmpiService registerEmpiService = SpringUtil.getBean(RegisterEmpiSerImpl.class); private DaGrJbxxDao daGrJbxxDao = SpringUtil.getBean(DaGrJbxxDao.class); private CountDownLatch dLatch; /** * 機(jī)構(gòu)代碼集合 */ private ListjgList; public DaGrJbxxEmpiRunnable(List threadJgLsit,CountDownLatch downLatch){ super(); jgList = threadJgLsit; dLatch = downLatch; } @Override public void run() { for(int i=0;i 調(diào)用接口實(shí)現(xiàn)類
import com.winning.jcfw.empi.dao.DaGrJbxxDao; import com.winning.jcfw.empi.service.DaGrJbxxService; import com.winning.jcfw.empi.thread.DaGrJbxxEmpiRunnable; import com.winning.jcfw.empi.util.ConvertListUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @ClassName DaGrJbxxSerImpl * @Description TODO * @Author WJX * @Date 2019/10/28 14:53 **/ @Service @Slf4j public class DaGrJbxxSerImpl implements DaGrJbxxService { @Autowired private DaGrJbxxDao daGrJbxxDao; @Override public void handleData(int perListCount) { int totalCount = daGrJbxxDao.getCount(); log.info("公衛(wèi)表 DA_GR_JBXX 表待生成記錄:" + totalCount + "條數(shù)據(jù)"); //機(jī)構(gòu)集合 ListjgList = daGrJbxxDao.getJgCount(); //線程機(jī)構(gòu)集合 List > threadjgList = ConvertListUtils.getjgLsit(jgList,perListCount); int threadCount = threadjgList.size(); ExecutorService executor = Executors.newFixedThreadPool(threadCount); //創(chuàng)建計(jì)數(shù)器對(duì)象,此處構(gòu)造器傳入的int類型實(shí)參,必須與下文需要的創(chuàng)建的子線程個(gè)數(shù)相同。 CountDownLatch latch = new CountDownLatch(threadCount); for(int k=0;k
yldmList = threadjgList.get(k); Runnable daGrJbxxEmpiRunnable = new DaGrJbxxEmpiRunnable(yldmList,latch); Thread daGrJbxxEmpiThread = new Thread(daGrJbxxEmpiRunnable); executor.execute(daGrJbxxEmpiThread); } try { latch.await();//保證之前的所有的線程都執(zhí)行完成,才會(huì)走下面的 } catch (InterruptedException e) { log.info("線程執(zhí)行異常",e); } } } CountDownLatch源碼解析:
/** * Constructs a {@code CountDownLatch} initialized with the given count. * * @param count the number of times {@link #countDown} must be invoked * before threads can pass through {@link #await} * @throws IllegalArgumentException if {@code count} is negative */ public CountDownLatch(int count) { if (count < 0) throw new IllegalArgumentException("count < 0"); this.sync = new Sync(count); }await方法
/** * Causes the current thread to wait until the latch has counted down to * zero, unless the thread is {@linkplain Thread#interrupt interrupted}. * *If the current count is zero then this method returns immediately. * *
If the current count is greater than zero then the current * thread becomes disabled for thread scheduling purposes and lies * dormant until one of two things happen: *
*
* *- The count reaches zero due to invocations of the * {@link #countDown} method; or *
- Some other thread {@linkplain Thread#interrupt interrupts} * the current thread. *
If the current thread: *
*
* then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * @throws InterruptedException if the current thread is interrupted * while waiting */ public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); }- has its interrupted status set on entry to this method; or *
- is {@linkplain Thread#interrupt interrupted} while waiting, *
sync.acquireSharedInterruptibly(1)
/** * Acquires in shared mode, aborting if interrupted. Implemented * by first checking interrupt status, then invoking at least once * {@link #tryAcquireShared}, returning on success. Otherwise the * thread is queued, possibly repeatedly blocking and unblocking, * invoking {@link #tryAcquireShared} until success or the thread * is interrupted. * @param arg the acquire argument. * This value is conveyed to {@link #tryAcquireShared} but is * otherwise uninterpreted and can represent anything * you like. * @throws InterruptedException if the current thread is interrupted */ public final void acquireSharedInterruptibly(int arg) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (tryAcquireShared(arg) < 0) doAcquireSharedInterruptibly(arg); } /** * Acquires in shared interruptible mode. * @param arg the acquire argument */ private void doAcquireSharedInterruptibly(int arg) throws InterruptedException { final Node node = addWaiter(Node.SHARED); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == head) { int r = tryAcquireShared(arg); if (r >= 0) { setHeadAndPropagate(node, r); p.next = null; // help GC failed = false; return; } } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) throw new InterruptedException(); } } finally { if (failed) cancelAcquire(node); } }
主要是parkAndCheckInterrupt()是如何將線程阻塞的
await方法使當(dāng)前線程等待直到count值為0,或者當(dāng)前線程被打斷!如果當(dāng)前的count值為0,那么await方法直接返回,當(dāng)前線程不會(huì)阻塞!如果當(dāng)前的count值大于0,那么當(dāng)前線程阻塞(線程調(diào)度機(jī)制無(wú)法給當(dāng)前線程分配CPU時(shí)間片),直到以下兩種情況任意一種發(fā)生為止:
count值通過(guò)countDown方法的調(diào)用達(dá)到0 或者 其他線程打斷了當(dāng)前線程
/** * Convenience method to park and then check if interrupted * * @return {@code true} if interrupted */ private final boolean parkAndCheckInterrupt() { LockSupport.park(this); return Thread.interrupted(); }
unparkSuccessor()方法喚醒線程
/** * Wakes up node's successor, if one exists. * * @param node the node */ private void unparkSuccessor(Node node) { /* * If status is negative (i.e., possibly needing signal) try * to clear in anticipation of signalling. It is OK if this * fails or if status is changed by waiting thread. */ int ws = node.waitStatus; if (ws < 0) compareAndSetWaitStatus(node, ws, 0); /* * Thread to unpark is held in successor, which is normally * just the next node. But if cancelled or apparently null, * traverse backwards from tail to find the actual * non-cancelled successor. */ Node s = node.next; if (s == null || s.waitStatus > 0) { s = null; for (Node t = tail; t != null && t != node; t = t.prev) if (t.waitStatus <= 0) s = t; } if (s != null) LockSupport.unpark(s.thread); }
最后我們來(lái)看一段最簡(jiǎn)單的使用park與unpark方法阻塞喚醒線程代碼:
public static void main(String[] args) { Thread t = new Thread(() -> { System.out.println("阻塞線程1"); LockSupport.park(); System.out.println("線程1執(zhí)行完啦"); }); t.start(); try { Thread.sleep(2000); System.out.println("喚醒線程1"); LockSupport.unpark(t); Thread.sleep(5000); System.out.println("主線程結(jié)束"); } catch (InterruptedException e) { e.printStackTrace(); } }
阻塞線程1
喚醒線程1
線程1執(zhí)行完啦
主線程結(jié)束
感謝各位的閱讀,以上就是“多線程執(zhí)行的過(guò)程”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)多線程執(zhí)行的過(guò)程這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!