1.继承Thread类
Thread类实际上实现了Runnable接口,在作用上与实现Runnable接口无异,只是写法的差异。但由于java是单继承的,使用实现Runnable接口的方法也便于多个线程访问同一资源,所以这种继承Thread类的实现方法一般不推荐使用,看看就好
具体代码如下
public class Test2 {
public static void main(String[] args) {
MyThread thread = new MyThread("继承Thread类");
thread.start();
}
}
public class MyThread extends Thread {
private String type;
MyThread(String type) {
super();
this.type = type;
}
@Override
public void run() {
System.out.println("type is:" + type);
}
}
2.实现Runnable接口
最常用的方法,用就对了
具体代码如下
public class Test2 {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable("实现Runnable接口");
Thread thread = new Thread(myRunnable);
thread.start();
}
}
public class MyRunnable implements Runnable {
private String type;
MyRunnable(String type) {
super();
this.type = type;
}
@Override
public void run() {
System.out.println("type is:" + type);
}
}
3.实现Callable接口
Runnable接口的强化版,实现的call()方法可以有返回值,用future.get()方法获取,还可以指定返回值类型,并且可以捕获异常
具体代码如下
public class Test2 {
public static void main(String[] args) {
MyCallable myCallable = new MyCallable("实现Callable接口");
//创建一个只有单个线程的线程池
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future<String> future = threadPool.submit(myCallable);
try {
//用get()方法获取线程执行的返回值
String typeMessage = future.get();
System.out.println(typeMessage);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
public class MyCallable implements Callable<String> {
private String type;
MyCallable(String type) {
super();
this.type = type;
}
@Override
public String call() throws Exception {
return "type is:" + type;
}
}
有任何问题和见解请留言