- 继承Thread,重写Thread类中的run方法;
package com.czxy.changgou3.thread;
/**
* Created by xiyou.
*/
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("my thread .....");
}
}
- 实现Runnable接口,实现run方法;
package com.czxy.changgou3.thread;
/**
* Created by xiyou.
*/
public class MyThread2 implements Runnable {
@Override
public void run() {
System.out.println("my 2222 ....");
}
}
- 通过Callable和FutureTask创建线程
package com.czxy.changgou3.thread;
/**
Created by xiyou.
*/
public class MyThread3 implements Callable<String>{
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
return null;
}
public static void main(String[] args) throws Exception {
MyThread3 c = new MyThread3();
FutureTask<String> future = new FutureTask<>(c);
Thread t = new Thread(future);
t.start();
...
String result = future.get(); //同步获取返回结果
System.out.println(result);
}
}
- 通过线程池创建线程
package com.czxy.changgou3.thread;
/**
Created by xiyou.
*/
public class MyThread4 implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("running");
}
public static void main(String[] args) {
MyThread4 task = new MyThread4();
ExecutorService ex = Executors.newCachedThreadPool();
ex.execute(task);
...
}
}
至于哪种方式更好===>实现Runnable接口更好:
①避免了Java单继承的局限性;
②把线程代码和任务的代码分离,解耦合(解除线程代码和任务的代码模块之间的依赖关系)。代码的扩展性非常好;
③实现Runnable接口可以更方便、灵活的实现数据的共享"