1.继承Thread类创建线程;
2.实现Runnable接口;
3.实现Callable接口的类的实例,用FutureTask类来包装。
一般推荐的是通过实现接口的方式,相对灵活一点,具体看情况,第3中写法相对麻烦一点,如果没有那个需求就没必要那么写。
实现方法比较简单,示例代码如下:
主程序测试类:
package concurrent.createThead;
import java.util.concurrent.FutureTask;
public class ThreadTest {
public static void main(String[] args) {
ThreadThead t1 = new ThreadThead("t1");
ThreadRunnable r2 = new ThreadRunnable();
Thread t2 = new Thread(r2);
ThreadCallable c3 = new ThreadCallable();
FutureTask<Object> f3 = new FutureTask<Object>(c3);
Thread t3 = new Thread(f3);
t1.start();
t2.start();
t3.start();
}
public static void doSomething(){
for (int i = 0; i < 100; i++) {
System.out.println("num-"+i + " "+ Thread.currentThread().getName());
}
}
}
三种写法:都需要覆盖对应的方法
继承Thread类:
package concurrent.createThead;
public class ThreadThead extends Thread{
public ThreadThead(String string) {
super(string);
}
@Override
public void run() {
System.out.println("thread..."+Thread.currentThread().getName());
ThreadTest.doSomething();
}
}
实现runnable接口:
package concurrent.createThead;
public class ThreadRunnable implements Runnable{
@Override
public void run() {
System.out.println("thread runnable..."+ Thread.currentThread().getName());
ThreadTest.doSomething();
}
}
实现Callable接口:
package concurrent.createThead;
import java.util.concurrent.Callable;
public class ThreadCallable implements Callable<Object>{
@Override
public Object call() throws Exception {
System.out.println("callable Thead..."+Thread.currentThread().getName());
ThreadTest.doSomething();
return "";
}
}