一 :继承Thread 类
public class ThreadDemo {
class MyThread extends Thread{
@Override
public void run() {
super.run();
System.out.println("开启线程");
}
}
public static void main(String[] args) {
ThreadDemo.MyThread myThread=new ThreadDemo().new MyThread();
myThread.start();
}
}
二:实现Runnable 接口
public class ThreadDemoRunable {
class MyRunable implements Runnable{
@Override
public void run() {
System.out.println( Thread.currentThread().getName()+"开启线程");
}
}
public static void main(String[] args) {
ThreadDemoRunable.MyRunable myRunable=new ThreadDemoRunable().new MyRunable();
Thread thread=new Thread(myRunable);
thread.setName("runnable ");
thread.start();
}
}
三:实现 Callable 接口
public class ThreadDemoCalladle {
class myCallable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
return 100;
}
}
public void startThreadByCallable(){
FutureTask futureTask=new FutureTask(new myCallable());
new Thread(futureTask).start();
try {
System.out.println(futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ThreadDemoCalladle().startThreadByCallable();
}
}
方法 | 差异 |
---|
继承 Thead | 实现简单,但是不能实现多继承 |
实现 Runnable | 实现也不算复杂,避免单一继承的缺点,数据共享 |
实现 Callable | 实现也稍稍复杂,避免单一继承的缺点,数据共享,相比Runnable 可以有返回值 |