java 核心编程——线程之线程的开发方法(二)
1.继承Thread类
Thread类是一个具体的类,不是抽象类。
package se.thread; import java.util.Date; public class ThreadTest extends Thread { public int time; public String name; ThreadTest(int time,String name){ this.name=name; this.time=time; } public void run(){ while(true){ try { System.out.println("用户"+this.name+"正在休息,时间:"+new Date()); Thread.sleep(this.time); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { ThreadTest threadTest1 = new ThreadTest(100,"jack"); threadTest1.start(); ThreadTest threadTest2 = new ThreadTest(200,"lolo"); threadTest2.start(); } }
2.实现Runable接口
package se.thread; import java.util.Date; public class TreadTest2 implements Runnable { public int time; public String name; public TreadTest2(int time,String name){ this.name=name; this.time=time; } @Override public void run() { while(true){ try { System.out.println("用户"+this.name+"正在休息,时间:"+new Date()); Thread.sleep(this.time); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { TreadTest2 threadTest2 = new TreadTest2(3000,"004"); TreadTest2 treadTest22 = new TreadTest2(2000,"125"); new Thread(threadTest2).start(); new Thread(treadTest22).start(); } }
3.选择Thread类还是Runable接口?
1.如果只是想重写Runable接口而不是重写Thread其他方法,则使用Runable接口。
2.如果子类继承了其他非Thread类,则只能通过实现Runable接口来实现run()的重写。
相关推荐
Lzs 2020-10-23
聚合室 2020-11-16
零 2020-09-18
Justhavefun 2020-10-22
jacktangj 2020-10-14
ChaITSimpleLove 2020-10-06
Andrea0 2020-09-18
周游列国之仕子 2020-09-15
afanti 2020-09-16
88234852 2020-09-15
YClimb 2020-09-15
风雨断肠人 2020-09-04
卖口粥湛蓝的天空 2020-09-15
stulen 2020-09-15
pythonxuexi 2020-09-06
abfdada 2020-08-26
梦的天空 2020-08-25