public class ExtendsThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("run "+i);
}
}
public static void main(String[] args) {
ExtendsThread thread = new ExtendsThread();
thread.start();
}
}
二、实现Runnable接口,重写run方法
public class ImplRunnable implements Runnable{
//重写run方法
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("runnable "+i);
}
}
public static void main(String[] args) {
//1.创建ImplRunnable对象
ImplRunnable implRunnable = new ImplRunnable();
//2.创建Thread对象,并将其implRunnable 传入其中
Thread thread = new Thread(implRunnable);
//3.启动线程
thread.start();
}
}
三、使用Lambda表达式
public static void main(String[] args) {
new Thread(() -> {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Lambda " + i);
}
}
}).start();
}
四、实现Callable接口,重写call方法,带有返回值
public class CallableTest implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i < 100; i++) {
sum += i;
}
return sum;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
//1.创建CallableTest
CallableTest callable = new CallableTest();
//2.创建FutureTask,传入callable
FutureTask<Integer> futureTask = new FutureTask<>(callable);
//3.创建Thread 传入futureTask
Thread thread = new Thread(futureTask);
//4.开启线程
thread.start();
//5.执行操作得到想要的结果
Integer sum = futureTask.get();
System.out.println(sum);
}
}
五、基于线程池构建线程
public static void main(String[] args) {
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("thread pool " +i);
}
});
for (int i = 0; i < 5; i++) {
System.out.println("main "+i);
}
service.shutdown();
}