2026/6/20 4:50:24
网站建设
项目流程
易讯网站建设,计算机二级网页设计考什么,外发加工网邀请码,最佳搜索引擎磁力王第十七章#xff1a;多线程
常见概念
进程和线程
进程#xff1a;运行中的程序
线程#xff1a;线程是由进程创建的#xff0c;是进程的一个实体#xff0c;当然线程也可以由线程创建#xff0c;如#xff1a;一个线程创建一个子线程
单线程和多线程
单线程#xff1a;…第十七章多线程常见概念进程和线程进程运行中的程序线程线程是由进程创建的是进程的一个实体当然线程也可以由线程创建如一个线程创建一个子线程单线程和多线程单线程同一个时刻只允许执行一个线程 多线程同一个时刻可以执行多个线程并发和并行并发同一个时刻多个任务交替执行(单核来回切换) 并行同一个时刻多个任务同时执行。多核CPU可以实现并行 并发和并行可以同时存在并行中又包含并发同步进而实现互斥线程 / 进程的同步和互斥同步协调多个并发实体执行的顺序 —进而实现—互斥控制多个并发实体不能同时访问同一个资源即要上锁多线程创建线程⭐实现Runnable接口重写run方法packagecom.lcz.mutithread.create;/** * author lcz * version 1.0 */publicclassThread02{publicstaticvoidmain(String[]args){DogdognewDog();ThreadthreadnewThread(dog);thread.start();}}classDogimplementsRunnable{privateintcount0;Overridepublicvoidrun(){while(true){System.out.println(小狗汪汪汪叫...(count));try{Thread.sleep(1000);}catch(InterruptedExceptione){thrownewRuntimeException(e);}if(count8){break;}}}}结束线程⭐自动结束线程完成任务后自动结束通知结束使用布尔变量来控制任务的结束进而线程结束packagecom.lcz.mutithread.exit;/** * author lcz * version 1.0 */publicclassExit01{publicstaticvoidmain(String[]args){DogdognewDog();ThreadthreadnewThread(dog);thread.start();try{Thread.sleep(10*1000);//主线程休眠10秒}catch(InterruptedExceptione){thrownewRuntimeException(e);}dog.setLoop(false);//通知退出子线程}}classDogimplementsRunnable{privateintcount0;privatebooleanlooptrue;publicvoidsetLoop(booleanloop){this.looploop;}Overridepublicvoidrun(){while(loop){System.out.println(小狗汪汪汪叫...(count));try{Thread.sleep(1000);}catch(InterruptedExceptione){thrownewRuntimeException(e);}if(count80){break;}}}}线程常用方法setNamegetNamesetPrioritygetPrioritysleep静态方法interruptyield静态方法线程的礼让让出cpu让其他线程执行但不一定成功取决于内核态资源是否紧张join线程的插队。插队的线程一旦插队成功则肯定先执行完插入的线程所有的任务细节1.线程优先级的范围 MAX_PRIORITY:10MIN_PRIORITY:1NORM_PRIORITY:52.interrupt中断线程但并没有真正的结束线程所以一般用于中断正在休眠线程3.sleep使当前线程休眠代码演示packagecom.lcz.mutithread.method;/** * author lcz * version 1.0 * 线程常用方法使用 */publicclassMethod{publicstaticvoidmain(String[]args){DogdognewDog();ThreadthreadnewThread(dog);thread.setName(lcz);thread.setPriority(Thread.NORM_PRIORITY);thread.start();for(inti0;i5;i){System.out.println(主线程i线程名字thread.getName()线程优先级thread.getPriority());try{Thread.sleep(1000);}catch(InterruptedExceptione){thrownewRuntimeException();}}thread.interrupt();//中断thread线程休眠}}classDogimplementsRunnable{privateintcount0;Overridepublicvoidrun(){while(true){System.out.println(小狗汪汪汪叫...(count));try{Thread.sleep(20000);}catch(InterruptedExceptione){}if(count50)break;}}}packagecom.lcz.mutithread.method;/** * author lcz * version 1.0 * 线程常用方法yield和join */publicclassMethod01{publicstaticvoidmain(String[]args)throwsInterruptedException{TtnewT();ThreadthreadnewThread(t);thread.start();for(inti0;i20;i){System.out.println(主线程(小弟)吃包子i);Thread.sleep(1000);if(i5){//thread.join();//子线程插队Thread.yield();}}}}classTimplementsRunnable{privateintcount0;Overridepublicvoidrun(){while(true){System.out.println(子线程(老大)吃包子 (count));try{Thread.sleep(1000);}catch(InterruptedExceptione){thrownewRuntimeException(e);}if(count20)break;}}}用户线程和守护线程用户线程也叫工作线程当线程的任务执行完或通知方式来结束守护线程一般是为工作线程服务的当所有的用户线程结束守护线程自动结束常见的守护线程垃圾回收机制thread.setDaemon(true); //将子线程设置为守护线程会随着用户线程(工作线程)结束而自动结束packagecom.lcz.mutithread.method;/** * author lcz * version 1.0 */publicclassMyDaemonThread{publicstaticvoidmain(String[]args)throwsInterruptedException{AanewA();ThreadthreadnewThread(a);thread.setDaemon(true);//将子线程设置为守护线程会随着用户线程(工作线程)结束而自动结束//守护线程作用:用于检测其他线程信息thread.start();for(inti0;i10;i){System.out.println(框框学习...i);Thread.sleep(500);}}}classAimplementsRunnable{Overridepublicvoidrun(){while(true){for(inti0;i10;i){System.out.println(嗷嗷难受...i);try{Thread.sleep(500);}catch(InterruptedExceptione){thrownewRuntimeException(e);}}}}}线程状态⭐线程生命周期1.new创建状态 2.Runnable可运行状态 (1):Ready就绪状态 (2):Running:运行状态 4.waiting等待状态等待某些资源 5.Blocked阻塞状态等待互斥锁 6.Terminated终止状态线程同步互斥机制⭐synchronized 关键字声明方法为同步方法 / 代码块为同步代码块即仅能一个线程访问访问时会为这个方法上一个互斥锁进而实现线程互斥同步的局限性导致程序的执行效率降低publicsynchronizedvoidm(Stringname){//需要被同步的代码}synchronized(this){//使用 this 对象互斥锁保证任一时刻只能有一个线程访问该对象//同步代码块得到对象互斥锁的线程才可执行同步代码块}解决超卖问题packagecom.lcz.mutithread.syn_;/** * author lcz * version 1.0 */publicclassSellTicket01extendsThread{privatestaticintcount100;publicsynchronizedstaticvoidsell(){//将静态方法声明为同步方法锁为当前类 SellTicket01.class//表示只有获得该锁才可执行下方同步代码while(true){if(count0)break;try{Thread.sleep(50);}catch(InterruptedExceptione){thrownewRuntimeException(e);}System.out.println(售票一张剩余票数(--count));}}Overridepublicvoidrun(){sell();}publicstaticvoidmain(String[]args){//不会出现超卖现象因为使用线程同步机制实现线程互斥SellTicket01sellTicket01newSellTicket01();SellTicket01sellTicket02newSellTicket01();SellTicket01sellTicket03newSellTicket01();sellTicket01.start();sellTicket02.start();sellTicket03.start();}}死锁现象⭐两个线程相互占有对方资源而想要获取对方已占有资源但无法获得对方资源就无法释放自身资源的情况编写程序要避免。packagecom.lcz.mutithread.syn_;/** * author lcz * version 1.0 */publicclassDeadLock{publicstaticvoidmain(String[]args){MyDeadLockDemomyDeadLockDemonewMyDeadLockDemo(true);ThreadAnewThread(myDeadLockDemo);A.setName(A线程);MyDeadLockDemomyDeadLockDemo1newMyDeadLockDemo(false);ThreadBnewThread(myDeadLockDemo1);B.setName(B线程);A.start();B.start();}}classMyDeadLockDemoimplementsRunnable{privatebooleanflag;privatestaticObjecto1newObject();privatestaticObjecto2newObject();publicMyDeadLockDemo(booleanflag){this.flagflag;}Overridepublicvoidrun(){if(flag){synchronized(o1){System.out.println(当前线程 Thread.currentThread().getName());synchronized(o2){System.out.println(当前线程 Thread.currentThread().getName());}}}else{synchronized(o2){System.out.println(当前线程 Thread.currentThread().getName());synchronized(o1){System.out.println(当前线程 Thread.currentThread().getName());}}}}}是否释放锁的几种情况会释放锁线程进入等待状态等待某些资源会释放锁不会释放锁sleep和 yield方法不会释放锁更多编程学习资源编程学习公众号【程序员论周】