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()的重写。
时间: 2024-10-03 22:54:49