首页 > 编程语言 > 详细

创建线程的三种方式及其优缺点

时间:2017-10-30 19:17:46      阅读:288      评论:0      收藏:0      [点我收藏+]
package testA;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ThreadTest {
    public static void main(String[] args) {
        // 1.继承Thread类
        new DefineThread().start();
        // 2.实现Runnable接口
        new Thread(new DefineRunnable()).start();
        // 3.实现Callable接口
        new Thread(futureTask).start();
        String result = "";
        try {
            result = futureTask.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(result);
    }

    static class DefineThread extends Thread {

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                String name2 = getName();
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(name2 + ": " + i);
            }
        }
    }

    static class DefineRunnable implements Runnable {

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                // String name2 = getName();
                String name = Thread.currentThread().getName(); // 实现runnable接口,使用Thread类的currentThread()获取当前线程对象
                try {
                    Thread.currentThread().sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(name + ": " + i);
            }
        }
    }

    static FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {

        @Override
        public String call() throws InterruptedException {
            String name = "";
            int i = 0;
            for (; i < 100; i++) {
                name = Thread.currentThread().getName();
                Thread.currentThread().sleep(100);
                System.out.println(name + ": " + i);
            }
            return name + " ----->Result=" + i;
        }
    });
}

 

1.继承Thread类,限制了该类的扩展性。

2.实现Runnable接口,该类还可以实现其他接口,开启新线程时可以共享同一个target对象。

//new Thread(target).start();

3.实现Callable接口,线程执行体可以有返回值,并且可以抛出异常。

创建线程的三种方式及其优缺点

原文:http://www.cnblogs.com/perkins/p/7755844.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!