1.继承Thread类
继承Thread类并重写run()方法
调用当前类对象的start()方法会自动启动线程并线程调用run方法。
public class Thread3 extends Thread{
@Override
public void run() {
super.run();
}
}
public void test3() throws InterruptedException {
Thread t3 = new Thread3();
t3.start();
}
2.实现runnable接口
与继承Thread类相似,实现run()方法。
public class Thread2 implements Runnable {
public Thread2(){
System.out.println("thread2 is creating......");
}
public void run() {
System.out.println("hahaha");
}
}
Thread t1 = new Thread(new Thread2(),"thread1");//参数1:开启的对象 参数2:线程的name
3.实现callable接口,带返回值类型为Callable<Object>
实现Callable接口的call()方法
将这个Callable接口实现类的对象作为参数传递到FutureTask类的构造器中,创建FutureTask类的对象。
将这个FutureTask类的对象作为参数传递到Thread类的构造器中,创建Thread类的对象,并调用这个对象的start()方法。
public class Thread5 implements Callable<String> {
public Object call() throws Exception {
System.out.println("hahahaha");
return "实现Callable接口的线程....";
}
}
public void test4() throws InterruptedException {
Thread5 thread5 = new Thread5();
FutureTask futureTask = new FutureTask(thread5);
Thread thread = new Thread(futureTask,"thread");
thread.start();
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/289611.html