Thread的定义有三种方式:继承Thread类,实现Runnable接口,实现Callable接口.
1、继承Thread类
package thread;
public class ThreadDemo {
public static void main(String[] args) {
new TDemo().start();
for (int i = 0; i < 20; i++) {
System.out.println("main " + i);
}
}
}
class TDemo extends Thread {
@Override
public void run() {//实现Tread类的run方法
for (int i = 0; i < 10; i++) {
System.out.println("Thread " + i);
}
}
}
2、实现Runnable接口
package thread;
public class RunnableDemo {
public static void main(String[] args) {
new Thread(new RDemo()).start();
for(int i = 0; i < 10; i++){
System.out.println("main() " + i);
}
}
}
class RDemo implements Runnable{
@Override
public void run() {
for (int i = 0; i < 9; i++) {
System.out.println("Thread " + i);
}
}
}
3、实现Callable接口
package thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableDemo {
public static void main(String[] args) throws Exception {
CDemo c = new CDemo();
ExecutorService es = Executors.newCachedThreadPool();
Future<String> f = es.submit(c);
System.out.println(f.get());
}
}
class CDemo implements Callable<String>{
@Override
public String call() throws Exception {
return "hahahhaha~~~~";
}
}
在线程的使用过程中,使用较多的是Runnable接口,其次是Thread类,只有在特别需要的环境下才会用到Callable接口!