码迷,mamicode.com
首页 > 编程语言 > 详细

Java多线程实现的四种方式

时间:2021-06-30 18:47:07      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:read   sys   nts   throw   rgs   ade   方式   adt   线程池   

1、继承Thread类:

 1 public class ThreadTest {
 2 
 3     static class ThreadA extends Thread {
 4 
 5         @Override
 6         public void run() {
 7             System.out.println(Thread.currentThread());
 8         }
 9 
10     }
11 
12     public static void main(String[] args) {
13         ThreadA a1 = new ThreadA();
14         ThreadA a2 = new ThreadA();
15         a1.start();
16         a2.start();
17     }
18 
19 }

2、实现Runnable接口:

 1 public class RunnableTest {
 2 
 3     static class ThreadRunnable implements Runnable {
 4 
 5         @Override
 6         public void run() {
 7             
 8             System.out.println(Thread.currentThread());
 9             
10         }
11         
12     }
13     
14     public static void main(String[] args) {
15         
16         Thread t1 = new Thread(new ThreadRunnable());
17         Thread t2 = new Thread(new ThreadRunnable());
18         t1.start();
19         t2.start();
20         
21     }
22     
23 }

3、实现Callable接口:

 1 public class CallableTest {
 2     
 3     static class ThreadCall implements Callable<String> {
 4 
 5         @Override
 6         public String call() throws Exception {
 7             System.out.println(Thread.currentThread());
 8             return "ss";
 9         }
10         
11     }
12     
13     public static void main(String[] args) throws Exception {
14         
15         FutureTask<String> ft = new FutureTask<>(new ThreadCall());
16         System.out.println(ft.get());
17         Thread t = new Thread(ft);
18         t.start();
19     }
20 
21 }

4、通过线程池创建线程:

 1 public class ExecutorTest {
 2     
 3     private static ExecutorService es = Executors.newCachedThreadPool();
 4     
 5     static class ThreadExecutor extends Thread {
 6         
 7         @Override
 8         public void run() {
 9             System.out.println(Thread.currentThread());
10         }
11         
12     }
13     
14     public static void main(String[] args) {
15     
16         es.execute(new ThreadExecutor());
17         es.execute(new ThreadExecutor());
18 
19     }
20 
21 }

 

Java多线程实现的四种方式

标签:read   sys   nts   throw   rgs   ade   方式   adt   线程池   

原文地址:https://www.cnblogs.com/bingl/p/14912826.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!