(1)多线程创建
创建多线程的方式
-
继承Thread类并重写run()方法
-
实现Runnable接口
-
实现Callabe接口
-
匿名内部类以及lambda表达式
-
线程池
-
Spring异步方法
-
定时器(java.util.Timer)
下面详细的介绍每种创建方式
1.继承Thread类并重写run()方法
public class CreatingThread01 extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName()+ " is running"); } public static void main(String[] args) { new CreatingThread01().start(); new CreatingThread01().start(); } }
2.实现Runnable接口
public class CreatingThread02 implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + " is running"); } public static void main(String[] args) { new Thread(new CreatingThread02()).start(); new Thread(new CreatingThread02()).start(); } }
3.实现Callabe接口
public class CreatingThread03 implements Callable<Long> { @Override public Long call() throws Exception { TimeUnit.SECONDS.sleep(1); System.out.println(Thread.currentThread().getName()+ " is running"); return Thread.currentThread().getId(); } public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask<Long> task = new FutureTask<>(new CreatingThread03()); new Thread(task).start(); System.out.println("等待完成任务"); Long result = task.get(); System.out.println("任务结果:" + result); } }
4.匿名内部类
public class CreatingThread04 { public static void main(String[] args) { // Runnable匿名类,实现其run()方法 new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " is running"); } }).start(); // 同上,使用lambda表达式 new Thread(() -> { System.out.println(Thread.currentThread().getName() + " is running"); }).start(); } }
5.线程池
public class CreatingThread05 { public static void main(String[] args) { ExecutorService threadPool = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { threadPool.execute(()-> System.out.println(Thread.currentThread().getName() + " is running")); } } }
6.Spring异步方法
首先,springboot启动类加上@EnableAsync注解
@SpringBootApplication @EnableAsync public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
然后方法加上@Async注解
@Service public class CreatingThread06Service { @Async public void call() { System.out.println(Thread.currentThread().getName() + " is running"); } }
测试用例
@RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) public class CreatingThread06Test { @Autowired private CreatingThread06Service creatingThread06Service; @Test public void test() { creatingThread06Service.call(); creatingThread06Service.call(); } }
7.定时器(java.util.Timer)
public class CreatingThread07 { public static void main(String[] args) { Timer timer = new Timer(); // 每隔1秒执行一次 timer.schedule(new TimerTask() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " is running"); } }, 0 , 1000); } }

浙公网安备 33010602011771号