多线程的4种实现方式

多线程的实现方式:
  • 1.implements Runnable

  • 2.extends Thread

  • 3.implements Callable

  • 4.线程池实现


众所周知,程序是线性执行的,如果某个执行片段需要大量时间去处理的话,就可以考虑开多线程去处理,避免主程序执行缓慢。接下来来看一下多线程实现的3种方式:


1.implements Runnable:
首先编写一个类并implements Runnable,用于执行你需要的步骤:
package cn.com.do1.dsf.modules.messagesendlog.service.thread;

import java.util.List;
import cn.com.do1.dsf.bean.pub.PubAuthSysGetUserInfoDetailPersonResponse;
import cn.com.do1.dsf.modules.appapi.entity.AccountEntity;
import cn.com.do1.dsf.modules.messagesendlog.service.AccountService;

/**
 *开启多线程
 */
public class SaveAccountThread implements Runnable{
   
   private AccountService accountService;
   
   private PubAuthSysGetUserInfoDetailPersonResponse personResponse;
   
   private static Object obj=new Object();
   
   public SaveAccountThread(AccountService accountService,PubAuthSysGetUserInfoDetailPersonResponse personResponse){
      this.accountService=accountService;
      this.personResponse=personResponse;
   }
   
   @Override
   public void run() {
      //插入数据
      saveAccount(personResponse);   
   }
   
   private void saveAccount(PubAuthSysGetUserInfoDetailPersonResponse personResponse){
      // 这里添加同步锁,保障线程安全
      synchronized (obj) {
         List<AccountEntity> list=accountService.getUserByCid(personResponse.getCid());
         if (list==null || list.size()==0){
            // 执行插入方法,插入数据库数据
         }
      }
   }
   
}
然后运行线程:
SaveAccountThread saveAccountThread=new SaveAccountThread(accountService,personResponseCopy);
Thread t=new Thread(saveAccountThread);
t.start();
2.extends Thread:
1.创建一个类,继承Thread:
public class ExtendsThread extends Thread {
    /**
     * 线程名称
     */
    private String threadName;
 
    /**
     * 构造函数
     * @param threadName 线程名称
     */
    public ExtendsThread(String threadName) {
        this.threadName = threadName;
    }
 
    /**
     * 重写run方式
     */
    @Override
    public void run() {
        System.out.println(threadName);
    }
}
2.运行:
ExtendsThread extendsThread = new ExtendsThread("1");
        extendsThread.start();
3.implements Callable:

实现Callable接口主要是可以获取到返回值,futureTask.get() 获取返回的值

1.创建类,implements Callable:
public class ThreadImplCallable<T> implements Callable<T> {
    /**
     * 线程名称
     */
    private String threadName;
 
    /**
     * 构造函数
     * @param threadName 线程名称
     */
    public ThreadImplCallable(String threadName) {
        this.threadName = threadName;
    }
    /**
     * 重写call方法
     */
    @Override
    public T call() throws Exception {
        System.out.println(threadName);
        return (T)threadName;
    }
}
2.执行线程,并获取返回值:
FutureTask<String> futureTask = new FutureTask<>(threadImplCallable);
        Thread thread = new Thread(futureTask);
        thread.start();
        String rValue = futureTask.get();
        System.out.println("Thread1 return value is " + rValue);

4.线程池实现:
public class ThreadDemo05{
 
    private static int POOL_NUM = 10;     //线程池数量
 
    /**
     * @param args
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        ExecutorService executorService = Executors.newFixedThreadPool(5);  
        for(int i = 0; i<POOL_NUM; i++)  
        {  
            RunnableThread thread = new RunnableThread();
 
            //Thread.sleep(1000);
            executorService.execute(thread);  
        }
        //关闭线程池
        executorService.shutdown(); 
    }   
 
}
 
class RunnableThread implements Runnable  
{     
    @Override
    public void run()  
    {  
        System.out.println("通过线程池方式创建的线程:" + Thread.currentThread().getName() + " ");  
 
    }  
}

今天的分享到此结束,以上就是多线程常用的3种实现方式,大家可根据实际业务进行扩展哦!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值