public class T4 {
public static void main(String[] args) {
System.out.println(Thread.currentThread());
Thread t1 = new A1();
t1.start();
}
}
class A1 extends Thread{
@Override
public void run() {
for(int i=0;i<10;i++) {
System.out.println("Thread:"+Thread.currentThread().getName());
}
}
}
2、实现Runnable接口
public class T3 {
public static void main(String[] args) {
System.out.println("Thread:"+Thread.currentThread().getName());
Thread t1 = new Thread(new A2());
t1.start();
}
}
class A2 implements Runnable{
@Override
public void run() {
int res =0;
for(int i=0;i<10;i++) {
res+=i;
System.out.println("Thread:"+Thread.currentThread().getName());
}
}
}
3、使用Callable和Future接口创建线程
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class T2 {
public static void main(String[] args) throws Exception {
System.out.println("Test3:" + Thread.currentThread().getName());
Callable c = new A4();
FutureTask ft = new FutureTask(c);
Thread t1 = new Thread(ft);
t1.start();
Object res = ft.get();
System.out.println("结果:" + res);
}
}
class A4 implements Callable {
@Override
public Object call() throws Exception {
int res = 0;
for (int i = 0; i < 10; i++) {
res += i;
System.out.println("Thread:" + Thread.currentThread().getName());
}
return res;
}
}