您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

JAVA--线程与多线程 图文详解

2024/6/8 18:58:51发布26次查看
【线程】java程序中的单任务流。我们把每个任务放在相对独立的线程中去实现。main是主线程
【并发】同时完成多个任务。程序执行的步骤都是有顺序的,但很多时候我们需要并发处理一个问题,而不是按顺序处理一个问题
【多线程】线程也看成对象,多线程指多个线程对象
【api中支持线程的类】java.lang.thread。thread类的对象就是线程对象
练习一、初始化线程对象,打印线程
package pkg3;public class test3 implements runnable{ thread th1; public test3() {//2 th1=new thread(this);//2-1初始化了线程对象 th1.start();//2-2启动了线程对象,自动调用run方法 } public static void main(string[] args){ new test3();//1.从主线程开始,调用构造方法 }@overridepublic void run() {//3 // todo auto-generated method stub system.out.println("线程运行了");//3-1打印线程,“运行了”}}
练习二、线程的生命周期:new、runnable、not runnable、dead
package pkg3;public class test3 implements runnable{ thread th1; public test3() {//2 th1=new thread(this);//2-1初始化了线程对象 th1.start();//2-2启动了线程对象,自动调用run方法 } public static void main(string[] args){ new test3();//1.从主线程开始,调用构造方法 }@overridepublic void run() {//3 // todo auto-generated method stub while(true) { system.out.println("线程运行了");//3-1打印线程,“运行了” try { th1.sleep(500);//强制睡眠500毫秒,进入非运行状态not runnable(睡眠、堵塞、排队) } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } }}}
练习三、多线程
package pkg3;public class test3 implements runnable{ thread th1,th2; public test3() {//2 th1=new thread(this);//2-1初始化了线程对象 th2=new thread(this); th1.start();//2-2启动了线程对象,自动调用run方法 th2.start(); } public static void main(string[] args){ new test3();//1.从主线程开始,调用构造方法 }@overridepublic void run() {//3 // todo auto-generated method stub /*while(true) { system.out.println("线程运行了");//3-1打印线程,“运行了” try { th1.sleep(500);//强制睡眠500毫秒,进入非运行状态not runnable(睡眠、堵塞、排队) } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } }*/ thread th=thread.currentthread();//这个方法可以判断进入run方法的线程对象 if(th==th1) { system.out.println("线程1运行了"); } if(th==th2) { system.out.println("线程2运行了"); }}}
相关推荐:
java -- 多线程
java线程详解及线程与进程的区别
以上就是java--线程与多线程 图文详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product