创建线程的四种方式
方式一:
public class Thread01 extends Thread{
@Override
public void run() {
System.out.println("当前执行的线程是"+Thread01.currentThread().getName());
}
public static void main(String[] args) {
Thread01 thread01 = new Thread01();
thread01.setName("我是线程名字");
thread01.start();
}
}
方式二:
public class Thread02 implements Runnable{
@Override
public void run() {
System.out.println("当前执行的线程是"+Thread01.currentThread().getName());
}
public static void main(String[] args) {
Thread02 thread02 = new Thread02();
Thread t1= new Thread(thread02,"线程一");
Thread t2= new Thread(thread02,"线程二");
t1.start();
t2.start();
}
}
方式三:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Thread03 implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("当前线程为:" + Thread.currentThread().getName());
return "哈哈哈";
}
public static void main(String[] args) {
FutureTask<String> task = new FutureTask<String>(new Thread03());
Thread thread = new Thread(task);
thread.setName("线程1");
thread.start();
String result;
try {
result = task.get();
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
方式四:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Thread04 {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(2);
service.execute(new Thread1());
Future<Integer> result = service.submit(new Thread2());
try {
Integer resultValue = result.get();
System.out.println(resultValue);
} catch (Exception e) {
e.printStackTrace();
}
service.shutdown();
}
}
class Thread1 implements Runnable {
@Override
public void run() {
System.out.println("我实现了Runnable接口完成的线程");
}
}
class Thread2 implements Callable<Integer> {
@Override
public Integer call() {
System.out.println("我实现了Callable接口完成的线程");
return 666;
}
}