创建线程的方式
1.Class Thread
package com.lisus2000.style;
public class Test01 extends Thread{
@Override
public void run() {
System.out.println("继承Thread类,重写run方法实现线程.");
}
public static void main(String[] args) throws InterruptedException {
Test01 t1 = new Test01();
t1.start();
Test01 t2 = new Test01();
t2.start();
Thread.sleep(10L);
System.out.println("main方法执行");
}
}
2.Interface Runnable
package com.lisus2000.style;
public class Test02 implements Runnable {
@Override
public void run() {
System.out.println("实现Runnable接口,覆盖run方法实现线程.");
}
public static void main(String[] args) {
Thread t1 = new Thread(new Test02());
t1.start();
Thread t2 = new Thread(new Test02());
t2.start();
System.out.println("main方法执行");
}
}
3.Interface Callable
package com.lisus.sytle;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Test03 implements Callable<String> {
@Override
public String call() throws Exception {
return "Thread execute.txt finished";
}
public static void main(String[] args) {
FutureTask<String> futureTask=new FutureTask<>(new Test03());
new Thread(futureTask).start();
try {
String result = futureTask.get();
System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.out.println("main方法执行");
}
}
4.Executors
package com.lisus.sytle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test04 implements Runnable{
@Override
public void run() {
System.out.println("线程执行");
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i=0;i<10;i++){
Test04 thread=new Test04();
executorService.execute(thread);
}
executorService.shutdown();
System.out.println("main方法执行");
}
}
5.ThreadPoolTaskExecutor
package com.bjpowernode.style;
import com.bjpowernode.service.MyService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@ComponentScan(basePackages = {"com.lisus2000.service"})
@EnableAsync
public class Test05 {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Test05.class);
MyService myService = context.getBean(MyService.class);
myService.test2();
System.out.println("主线程执行结束......");
}
}