• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

江湖丶浪子

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

Java多线程实现的四种方式

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 }

 

posted on 2021-06-30 16:07  江湖丶浪子  阅读(694)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3