线程创建的三种方式

线程的创建有三种方式:extends Thread,implements Callable,implements Runnable

1.继承Thread


 
    public class MyThread extends Thread {
    private String name;

    public MyThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0;i<100;i++){
            System.err.println(name+"-->"+i);
        }
    }
}   

2.实现Runnable(推荐使用)


 
public class MyRunnable implements  Runnable {
    private String name;

    public MyRunnable(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0;i<100;i++){
            System.err.println(name+"-->"+i);
        }
    }
}

3.实现Callable


 
public class MyCallable implements Callable{
    private String name;

    public MyCallable() {
    }

    public MyCallable(String name) {
        this.name = name;
    }

    @Override
    public String call() {
        for (int i = 0;i<100;i++){
            System.err.println(name+"-->"+i);
        }
        return "逻辑执行完毕!";
    }
}

4.启动线程


public class TestMain {

    public static void main(String args[]) throws ExecutionException, InterruptedException {
        //thread();
        //runnable();

        //callable();

        //多线程两种实现方式的区别
        //1.使用runnable 接口与Threa类相比,避免了Thread类单继承的局限
        //2.Thread类实现了runbale接口
        //3使用 runnable接口  类似代理模式
    }

    private static void callable() throws InterruptedException, ExecutionException {
        MyCallable myCallable = new MyCallable("线程A");
        FutureTask task = new FutureTask(myCallable);

        new Thread(task).start();
        System.err.println("A-->"+task.get());
    }

    private static void runnable() {
        MyRunnable myRunnable1 = new MyRunnable("线程1");
        MyRunnable myRunnable2 = new MyRunnable("线程2");
        MyRunnable myRunnable3 = new MyRunnable("线程3");
        new Thread(myRunnable1).start();
        new Thread(myRunnable2).start();
        new Thread(myRunnable3).start();
    }

    private static void thread() {
        MyThread m1 = new MyThread("线程1");
        MyThread m2 = new MyThread("线程2");
        MyThread m3 = new MyThread("线程3");

        m1.start();
        //多次启动抛出  java.lang.IllegalThreadStateException
        // m1.start();
        m2.start();
        m3.start();
    }
}

Thread和Runnable 区别:

  1. Thread类实现了Runnable 接口,使用Runnable 避免了Thread单继承的局限性。
  2. Runnable 使用Runnable 更能提现数据共享这一概念。
posted @ 2018-02-22 13:01  xiaofei001  阅读(179)  评论(0)    收藏  举报