当前位置: 首页 > 后端技术 > Java

线程相关的一些基本概念

时间:2023-04-01 22:35:47 Java

1.程序QQ、微信等应用都是程序。二、进程进程是一个程序运行的状态。3.线程线程是一个进程中不同的执行路径。更专业的解释:进程是OS分配资源的基本单位,线程是执行调度的基本单位。分配资源最重要的是:开辟一块独立的内存空间,然后调度线程的执行(即线程共享进程的内存空间,没有自己独立的内存空间)。第四,纤程/协程是用户态线程。线程;fiber的切换和调度不需要经过内核,线程切换在内核态完成。1、与线程相比,纤程特点1)占用资源少,一般OS线程占用1M,纤程4K2)切换比较简单5、创建线程的方法1、继承Thread类2、实现Runnable接口3、通过Executor线程池creation/***@authorJava与算法学习:周一*/}}privatestaticclassMyRunimplementsRunnable{@Overridepublicvoidrun(){System.out.println("MyRun");}}publicstaticvoidmain(String[]args){newMyThread().start();新线程(新的MyRun())。开始();newThread(()->{System.out.println("lambda...");}).start();}}六、常用的线程方法1、Sleep方法yield当前正在执行的线程,供其他线程运行。2、Yield方法谦虚退出,即yieldCPU;该线程会进入该线程的等待队列,CPU可能会再次执行该线程,但更大的可能性是执行其他线程。3.Join方法停止执行当前线程,转而执行加入线程/***@authorJava与算法学习:Monday*/publicclassSleepYieldJoin{publicstaticvoidmain(String[]args){//testSleep();//测试收益率();测试连接();}staticvoidtestSleep(){newThread(()->{for(inti=0;i<10;i++){System.out.println("SleepA"+i);try{Thread.sleep(1);}catch(InterruptedExceptione){e.printStackTrace();}}}).start();newThread(()->{for(inti=0;i<100;i++){System.out.println("SleepB"+i);}}).start();}staticvoidtestYield(){newThread(()->{for(inti=0;i<10;i++){System.out.println("yieldA"+i);if(i%2==0){Thread.yield();}}})。开始();newThread(()->{for(inti=0;i<10;i++){System.out.println("yieldB"+i);if(i%2==0){Thread.yield();}}})。开始();}staticvoidtestJoin(){Threadt1=newThread(()->{for(inti=0;i<10;i++){System.out.println("A"+i);try{Thread.sleep(300);}catch(InterruptedExceptione){e.printStackTrace();}}});Threadt2=newThread(()->{try{t1.join();}catch(InterruptedExceptione){e.printStackTrace();}for(inti=0;i<10;i++){System.out.println("B"+i);试试{Thread.sleep(300);}catchh(InterruptedExceptione){e.printStackTrace();}}});Threadt3=newThread(()->{try{t2.join();}catch(InterruptedExceptione){e.printStackTrace();}for(inti=0;i<10;i++){System.out.println("c"+i);try{Thread.sleep(300);}catch(InterruptedExceptione){e.printStackTrace();}});//不管t1,t2,t3的启动顺序如何,输出的结果都是一样的,可以保证t1,t2,t3顺序执行t3.start();t2.开始();t1.开始();}}