JAVA之线程实现方式Test代码练习

线程实现方式有四种,大型项目基本使用线程池,简要罗列代码块。

1、继承Thread类创建线程

/**
 * @author yto_yh
 *
 */
public class TestThread090601 extends Thread{
    
    /* (non-Javadoc)
     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        System.out.println("线程启动");
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TestThread090601 t=new TestThread090601();
        TestThread090601 t1=new TestThread090601();
        t.start();
        t1.start();
    }

}

2.实现Runnable接口创建线程


/**
 * @author yto_yh
 *
 */
public class TestThread90602 implements Runnable{
    public void run() {
        System.out.println("线程启动");
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TestThread90602 tt=new TestThread90602();
        Thread t=new Thread(tt);
        t.start();
        Thread t1=new Thread(tt);
        t1.start();
    }

}

3、使用ExecutorService、Callable、Future实现有返回结果的线程

/**
 * @author yto_yh
 *
 */
public class TestCallable0903 implements Callable<Object>{
    

    private int threadNum;
    TestCallable0903(Integer threadNum){
        this.threadNum=threadNum;
    }
    /* (non-Javadoc)
     * @see java.util.concurrent.Callable#call()
     */
    @Override
    public Object call() throws Exception {
        System.out.println("第"+threadNum+"个线程启动!");
        return "第"+threadNum+"个线程结束!";
    }
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        int taskSize = 5;  
        ExecutorService pool = Executors.newFixedThreadPool(taskSize);  
        List<Future> list = new ArrayList<Future>();  
        for (int i = 0; i < taskSize; i++) {  
             Callable c = new TestCallable0903(i);  
             Future f = pool.submit(c);  
             list.add(f);  
        }  
        pool.shutdown();  
        for (Future f : list) {  
            System.out.println(">>>" + f.get().toString());  
        }  
    }
}

/**
 * @author yto_yh
 *
 */
public class TestCallable90302 {

    /**
     * @param args
     * @throws ExecutionException 
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException, ExecutionException {
      int threadNum=3;//创建线程数量
      List<Future> list =new ArrayList<Future>();
      ExecutorService executorService=Executors.newFixedThreadPool(threadNum);//创建线程池
      for(int i=0;i<threadNum;i++) {
         //提交有返回类型的任务
         Future f= executorService.submit((Callable)(new MyCallable(i+" ")));
         list.add(f);
      }
     executorService.shutdown(); 
    //遍历返回值
     list.forEach(s->{
        try {
            System.out.println(s.get().toString());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
      });
    }
}




/**
 * @author yto_yh
 *
 */
public class MyCallable implements Callable<Object>{
    
    private String taskNum;  
    
    MyCallable(String taskNum) {  
       this.taskNum = taskNum;  
    } 
    @Override
    public Object call() throws Exception {
        // TODO Auto-generated method stub
        System.out.println(">>>" + taskNum + "任务启动");  
        Date dateTmp1 = new Date();  
        Thread.sleep(1000);  
        Date dateTmp2 = new Date();  
        long time = dateTmp2.getTime() - dateTmp1.getTime();  
        System.out.println(">>>" + taskNum + "任务终止");  
        return taskNum + "任务返回运行结果,当前任务时间【" + time + "毫秒】";  
    }
  //实现call()方法,作为线程执行体
/*    public Integer call(){
        int i = 5;
        for( ; i<100 ; i++){
            System.out.println(Thread.currentThread().getName() + "的循环变量i的值:" +i);
        }
        //call()方法可以有返回值
        return i;
    }
    
    public static void main(String[] args) {
      //创建Callable对象
        Callable cd = new MyCallable();
        //使用FutureTask来包装Callable对象
        FutureTask<Integer> task = new FutureTask<Integer>(cd);
        for(int i=0 ; i<100 ; i++){
            System.out.println(Thread.currentThread().getName() + "的循环变量i的值:" +i);
            if(i==20){
                //实质还是以Callable对象来创建并启动线程
                new Thread(task,"有返回值的线程").start();
            }
        }
        try{
            System.out.println("子线程的返回值" + task.get());
            
        }catch(Exception e){
            e.printStackTrace();
        }
*/
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值