说说线程有几种创建方式?
Java中创建线程主要有三种方式:
- 定义Thread类的子类,并重写该类的run方法
/**
* 继承Thread-重写run方法
* Created by BaiLi
*/
public class BaiLiThread {
public static void main(string[] args) {
MyThread myThread = new MyThread();
myThread.run();
}
}
class MyThread extends Thread {
@Override
public void run() {
System.out.println("一键三连");
}
}
- 定义Runnable接口的实现类,并重写该接口的run()方法
/**
* 实现Runnable-重写run()方法
* Created by BaiLi
*/
public class BaiLiRunnable {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
new Thread(myRunnable).start();
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("一键三连");
}
}
- 定义Callable接口的实现类,并重写该接口的call()方法,一般配合FutureTask使用
/**
* 实现Callable-重写call()方法
* Created by BaiLi
*/
public class BaiLiCallable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> ft = new FutureTask<String>(new MyCallable());
Thread thread = new Thread(ft);
thread.start();
System.out.println(ft.get());
}
}
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "一键三连";
}
}