Java提供多种方式创建线程
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;@Slf4j
public class MyTest {@Testpublic void test() {MyThread myThread=new MyThread();myThread.start();}
}@Slf4j
class MyThread extends Thread {@Overridepublic void run() {log.info("自定义线程");}
}
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;@Slf4j
public class MyTest {@Testpublic void test() {MyThread myThread = new MyThread();Thread thread = new Thread(myThread);thread.start();}
}@Slf4j
class MyThread implements Runnable {@Overridepublic void run() {log.info("自定义线程");}
}
或
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;@Slf4j
public class MyTest {@Testpublic void test() {Thread thread = new Thread(new Runnable() {@Overridepublic void run() {log.info("自定义线程");}});thread.start();}
}
或
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;@Slf4j
public class MyTest {@Testpublic void test() {Thread thread = new Thread(() -> log.info("自定义线程"));thread.start();}
}
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;@Slf4j
public class MyTest {@Testpublic void test() {try {MyThread myThread = new MyThread();FutureTask futureTask = new FutureTask<>(myThread);Thread thread = new Thread(futureTask);//启动线程thread.start();//获取线程返回值String s = futureTask.get();log.info(s);} catch (InterruptedException | ExecutionException e) {e.printStackTrace();Thread.currentThread().interrupt();}}
}@Slf4j
class MyThread implements Callable {@Overridepublic String call() throws Exception {log.info("自定义线程");return "自定义线程执行完毕";}
}
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import java.util.concurrent.*;@Slf4j
public class MyTest {@Testpublic void test() {ExecutorService executorService = Executors.newSingleThreadExecutor();MyThread myThread=new MyThread();executorService.execute(myThread);}
}@Slf4j
class MyThread implements Runnable {@Overridepublic void run() {log.info("自定义线程");}
}
线程主要包括以下几个状态: