java多线程的实现

1、继承Thread类实现多线程

2、实现Runnable接口方式实现多线程
如果自己的类已经extends另一个类,就无法直接extends Thread,

此时,必须实现一个Runnable接口。

3、使用ExecutorService、Callable、Future实现有返回结果的多线程
ExecutorService、Callable、Future这个对象实际上都是属于Executor框架中的功能类。
返回值的任务必须实现Callable接口,类似的,无返回值的任务必须Runnable接口。
执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了。

Executors类,提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口。
public static ExecutorService newFixedThreadPool(int nThreads)
创建固定数目线程的线程池。
public static ExecutorService newCachedThreadPool()
创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
public static ExecutorService newSingleThreadExecutor()
创建一个单线程化的Executor。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。

ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成。

package executor;

import java.util.ArrayList;  
import java.util.List;  
import java.util.Random;  
import java.util.concurrent.Callable;  
import java.util.concurrent.ExecutionException;  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
import java.util.concurrent.Future;  
  
public class ExecutorServiceTest {  
    public static void main(String[] args) {  
        ExecutorService executorService = Executors.newCachedThreadPool();  
        List<Future<String>> resultList = new ArrayList<Future<String>>();  
        // 创建10个任务并执行  
        for (int i = 0; i < 10; i++) {  
            // 使用ExecutorService执行Callable类型的任务,并将结果保存在future变量中  
            Future<String> future = executorService.submit(new TaskWithResult(i));  
            // 将任务执行结果存储到List中  
            resultList.add(future);  
        }  
        executorService.shutdown();  

        // 遍历任务的结果  
        for (Future<String> fs : resultList) {  
            try {  
                System.out.println(fs.get()); // 打印各个线程(任务)执行的结果  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            } catch (ExecutionException e) {  
                executorService.shutdownNow();  
                e.printStackTrace();  
                return;
            }
        }  
    }  
}  

/***
 * 多线程实现
 */
class TaskWithResult implements Callable<String> {  
    private int id;  
  
    public TaskWithResult(int id) {  
        this.id = id;  
    }  
  
    /** 
     * 任务的具体过程,一旦任务传给ExecutorService的submit方法,则该方法自动在一个线程上执行。      *  
     * @return 
     * @throws Exception 
     */  
    public String call() throws Exception {  
        System.out.println("call()方法被自动调用,干活!!!  " + Thread.currentThread().getName());  
        if (new Random().nextBoolean())  
            throw new TaskException("Meet error in task." + Thread.currentThread().getName());  
        // 一个模拟耗时的操作  
        for (int i = 999; i > 0; i--)
        ;  
        return "call()方法被自动调用,任务的结果是:" + id + " " + Thread.currentThread().getName();  
    }
}
/***
 * 自定义异常
 */
class TaskException extends Exception {
	private static final long serialVersionUID = 1L;

	public TaskException(String message) {
        super(message);
    }
}

实际应用

package executor;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;

public class ExecutorTest {
	
	private static final Logger logger=Logger.getLogger(ExecutorTest.class);
	public static void main(String[] args) {
		ExecutorCallTest();
//		ExecutorRunTest();
	}
	
	/****
	 * 有返回值
	 */
	public static void ExecutorCallTest() {
		ExecutorService executorservice =  Executors.newFixedThreadPool(10);
        List<Future<String>> resultList = new ArrayList<Future<String>>();
        List<String> listStr=new ArrayList<String>();//主键集合
        for(int i=0;i<10;i++){
        	listStr.add(i,i+"");
        }     
		for (int i=0;i<listStr.size();i++) {
			final String pk=listStr.get(i);//
			Future<String> future=executorservice.submit(new Callable<String>() {
				public String call() throws Exception {
					/**创建对象**/
//					Calculator calculator=new Calculator();
//					String resultStr= calculator.sum(pk, "10");
					/**调用静态方法**/
					String resultStr= Calculator.staticSum(pk, "10");
					logger.info("call()方法被自动调用,干活!!! " + Thread.currentThread().getName());
					return resultStr;
				}			
			});
			resultList.add(future);
		}
		//resultList 遍历结果集合 查看处理情况
		for(int j=0;j<resultList.size();j++){
			try {				
				logger.info("处理结果==="+resultList.get(j).get());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}		
		}
		executorservice.shutdown();
	}
	
	/****
	 * 无返回值
	 */
	public static void ExecutorRunTest() {
		ExecutorService executorservice =  Executors.newFixedThreadPool(10);
		for (int i=0;i<100;i++) {
			executorservice.submit(new Runnable() {
				public void run() {
					//业务方法
					logger.info("run()方法被自动调用,干活!!!  " + Thread.currentThread().getName());  
				}
			});
		}
		executorservice.shutdown();
	}
}

class Calculator{
	
	public String sum(String number1,String number2){
		BigDecimal bigNum1=new BigDecimal(number1);
		BigDecimal bigNum2=new BigDecimal(number2);
		BigDecimal bigSum=bigNum1.add(bigNum2);		
		return bigSum.toString();
	}
	
	public static String staticSum(String number1,String number2){
		BigDecimal bigNum1=new BigDecimal(number1);
		BigDecimal bigNum2=new BigDecimal(number2);
		BigDecimal bigSum=bigNum1.add(bigNum2);		
		return bigSum.toString();
	}
}

控制台输出

INFO - call()方法被自动调用,干活!!! pool-1-thread-10
INFO - call()方法被自动调用,干活!!! pool-1-thread-5
INFO - call()方法被自动调用,干活!!! pool-1-thread-3
INFO - call()方法被自动调用,干活!!! pool-1-thread-9
INFO - call()方法被自动调用,干活!!! pool-1-thread-6
INFO - call()方法被自动调用,干活!!! pool-1-thread-4
INFO - call()方法被自动调用,干活!!! pool-1-thread-1
INFO - call()方法被自动调用,干活!!! pool-1-thread-7
INFO - call()方法被自动调用,干活!!! pool-1-thread-8
INFO - call()方法被自动调用,干活!!! pool-1-thread-2
INFO - 处理结果===10
INFO - 处理结果===11
INFO - 处理结果===12
INFO - 处理结果===13
INFO - 处理结果===14
INFO - 处理结果===15
INFO - 处理结果===16
INFO - 处理结果===17
INFO - 处理结果===18
INFO - 处理结果===19

转载:http://blog.csdn.net/yuzhiboyi/article/details/7775266


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值