java thread callable runnable future demo

Java

2017-12-11

54

0

技术:java8

运行环境:IDEA 15.2 + jdk8 + windows 10

demo功能:提供java线程使用demo

Thread demo

public class ThreadTask extends Thread {
    @Override
    public void run() {
        long now = System.currentTimeMillis();
        System.out.println("ThreadTask:我的任务是输出当前的时间1=" + now);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        now = System.currentTimeMillis();
        System.out.println("ThreadTask:我的任务是输出当前的时间2=" + now);
    }
}

Runnable demo

/**
 * Created by francis on 2017/12/11.
 */
public class RunnableTask implements Runnable {
    @Override
    public void run() {
        long now = System.currentTimeMillis();
        System.out.println("RunnableTask:我的任务是输出当前的时间1=" + now);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        now = System.currentTimeMillis();
        System.out.println("RunnableTask:我的任务是输出当前的时间2=" + now);
    }
}

Callable Future demo

 public static void test3() {
        Callable callable = new Callable() {
            public Integer call() throws Exception {
                return new Random().nextInt(100);
            }
        };
        FutureTask future = new FutureTask(callable);
        new Thread(future).start();
        try {
            Thread.sleep(5000);// 可能做一些事情
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

问题:Callable Runnable 区别

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think