Java多线程实现的四种方式

1、继承Thread类:

public class ThreadTest {

    static class ThreadA extends Thread {

        @Override
        public void run() {
            System.out.println(Thread.currentThread());
        }

    }

    public static void main(String[] args) {
        ThreadA a1 = new ThreadA();
        ThreadA a2 = new ThreadA();
        a1.start();
        a2.start();
    }

}

2、实现Runnable接口:无返回值,不用抛异常

public class RunnableTest {

    static class ThreadRunnable implements Runnable {

        @Override
        public void run() {

            System.out.println(Thread.currentThread());

        }

    }

    public static void main(String[] args) {

        Thread t1 = new Thread(new ThreadRunnable());
        Thread t2 = new Thread(new ThreadRunnable());
        t1.start();
        t2.start();

    }

}

3、实现Callable接口:有返回值,需要抛异常

public class CallableTest {

    static class ThreadCall implements Callable {

        @Override
        public String call() throws Exception {
            System.out.println(Thread.currentThread());
            return "ss";
        }

    }

    public static void main(String[] args) throws Exception {

        FutureTask ft = new FutureTask<>(new ThreadCall());
        System.out.println(ft.get());
        Thread t = new Thread(ft);
        t.start();
    }

}

4、通过线程池创建线程:

4.1 Executor

public class ExecutorTest {

    private static ExecutorService es = Executors.newCachedThreadPool();

    static class ThreadExecutor extends Thread {

        @Override
        public void run() {
            System.out.println(Thread.currentThread());
        }

    }

    public static void main(String[] args) {

        es.execute(new ThreadExecutor());
        es.execute(new ThreadExecutor());

    }

}

4.2 ThreadPoolExcutor

ThreadPoolExcutor_风过茶易凉的博客-CSDN博客_threadpoolexcutor

小总结:线程类只是实现了Runnable或者Callable接口,还可以继承其他类。这种方式下,多个线程可以共享一个target对象,所以非常适合多个相同线程来处理同一份资源的情况,从而可以将CPU、代码和数据分开,形成清晰的模型,较好的体现了面向对象的思想。

你可能感兴趣的:(java,java,开发语言)