• Callable--创建有返回值的线程


    转自:JAVA 笔记 Callable 与 FutureTask:有返回值的多线程

     常用的Thread类在run方法执行完之后是没有返回值的,要实现子线程完成任务后返回值给主线程需要借助第三方转存。Callable接口则提供了一种有返回值的多线程实现方法。下面以一个简单的地主、监工和长工的例子展示这种接口的用法。

    长工类:

    长工类实现了Callable接口,线程运行完成后返回一个Integer值。 

    package com.lk.C;
    
    import java.util.concurrent.Callable;
    
    public class Changgong implements Callable<Integer>{
    //泛型限制了重写方法的返回值类型
        private int hours=12;
        private int amount;
        
        @Override
        public Integer call() throws Exception {
            while(hours>0){
                System.out.println("I'm working......");
                amount ++;
                hours--;
                Thread.sleep(1000);
            }
            return amount;
        }
    }

    地主:主进程

    监工:FutureTask 

    package com.lk.C;
    
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.FutureTask;
    
    
    public class Dizhu {
            
        public static void main(String args[]){
            Changgong worker = new Changgong();
            FutureTask<Integer> jiangong = new FutureTask<Integer>(worker);
            new Thread(jiangong).start();
            while(!jiangong.isDone()){
                try {
                    System.out.println("看长工做完了没...");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            int amount;
            try {
                amount = jiangong.get();
                System.out.println("工作做完了,上交了"+amount);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            
        }
    }
    I'm working......
    看长工做完了没...
    I'm working......
    看长工做完了没...
    看长工做完了没...
    I'm working......
    看长工做完了没...
    I'm working......
    I'm working......
    看长工做完了没...
    I'm working......
    看长工做完了没...
    看长工做完了没...
    I'm working......
    I'm working......
    看长工做完了没...
    看长工做完了没...
    I'm working......
    I'm working......
    看长工做完了没...
    I'm working......
    看长工做完了没...
    看长工做完了没...
    I'm working......
    看长工做完了没...
    工作做完了,上交了12
  • 相关阅读:
    动态为datagrid增加控件
    对DataGrid中的ListBox设置值
    Enhancing Inserting Data through the DataGrid Footer, Part 2
    Setting Focus to a TextBox in an EditItemTemplate
    Enhancing Inserting Data through the DataGrid Footer
    CRM选择行变色
    【转】on delete cascade
    VS如何连接2种类型的数据库
    SQL Server 已配置为允许远程连接 解决办法
    【转】sql server 重命名表字段
  • 原文地址:https://www.cnblogs.com/luankun0214/p/4399057.html
Copyright © 2020-2023  润新知