package com.example.xushuai.test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
/**
* @author xushuai
* @date 2023年04月29日 14:11
*/
//继承Thread类
public class ThreadTest extends Thread{
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
threadTest.start();
}
@Override
public void run() {
System.out.println("hello");
}
}
//实现runnable接口
class ThreadTestRunAble implements Runnable{
public static void main(String[] args) {
Thread threadTest = new Thread(new ThreadTest());
threadTest.start();
}
@Override
public void run() {
System.out.println("====run===");
}
}
//匿名内部类实现runnable接口
class ThreadTestRunAbleNoOne{
public static void main(String[] args) {
Thread threadTest = new Thread(new ThreadTest(){
@Override
public void run() {
System.out.println("====noone===");
}
});
threadTest.start();
}
}
//lambda表达式
class ThreadTestlambda{
public static void main(String[] args) {
Thread threadTest = new Thread(()->{
System.out.println("===lambda===");
});
threadTest.start();
}
}
//实现Callable,结合FutureTask ,可以拿到任务的执行结果
// (FutureTask 实现了 RunnableFuture,RunnableFuture又继承了 Runnable和Future接口,类与类之间单继承,接口之间可以多继承)
class ThreadTestCallable implements Callable<String> {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> stringFutureTask = new FutureTask<>(new ThreadTestCallable());
Thread thread = new Thread(stringFutureTask);
thread.start();
String s = stringFutureTask.get();
System.out.println("===s==="+s);
}
@Override
public String call() throws Exception {
return "===Callable===";
}
}
//线程池创建
class ThreadTestPool implements Runnable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new ThreadTestPool());
}
@Override
public void run() {
System.out.println("====pool====");
}
}
java创建线程执行任务的方式
最新推荐文章于 2024-02-18 18:25:49 发布