public class ThreadLearning {
//------------------------继承Thread类-----------------------
//匿名内部类的形式
@org.junit.Test
public void generateThread_1() {
Thread thread = new Thread() {
@Override
public void run() {
//do something
System.out.println("1");
}
};
thread.start();
}
//正常形式
@org.junit.Test
public void generateThread_2() {
Thread1 thread1 = new Thread1();
thread1.start();
}
class Thread1 extends Thread{
@Override
public void run() {
//do something
System.out.println("2");
}
}
//------------------------实现Runnable接口-----------------------
//匿名内部类的形式
@org.junit.Test
public void generateThread_3() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
//do something
System.out.println("1");
}
});
thread.start();
}
//正常形式
@org.junit.Test
public void generateThread_4() {
Thread2 thread2 = new Thread2();
Thread thread = new Thread(thread2);
thread.start();
}
class Thread2 implements Runnable{
@Override
public void run() {
//do something
System.out.println("2");
}
}
//------------------------实现Callable接口-----------------------
@org.junit.Test
public void generateThread_5() {
Thread3 thread3 = new Thread3();
FutureTask<String> futureTask = new FutureTask<String>(thread3);
new Thread(futureTask).start();
try {
String s = futureTask.get();
System.out.println(s);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
class Thread3 implements Callable<String>{
@Override
public String call() throws Exception {
return "我是实现Callable接口的线程类";
}
}
}