美文网首页
Java 多线程 Runnable、Future、Thread

Java 多线程 Runnable、Future、Thread

作者: LucasHao | 来源:发表于2020-03-04 16:03 被阅读0次

Runnable Thread

Runnable是接口,用来实现的;Thread是类,用来继承的;

一个需要多个线程并行共同执行的任务需要Runnable;而多个一致彼此独立的线程工作需要Thread;

对于Thread来说多个thread实例的运行彼此独立:

package CouncurrentDemo;

public class ThreadDemo {
    static class MyThread extends Thread{
        public  int count = 3;
        public synchronized void run(){
            while(count>0){System.out.println("excuting:"+count--);}
        }
    }
    public static void main(String[] args) {
        MyThread mythread=new MyThread();
        MyThread mythread2=new MyThread();
        mythread.start();
        mythread2.start();
    }
}
输出
excuting:3
excuting:3
excuting:2
excuting:2
excuting:1
excuting:1

Runnable通过一个Runnable实例在多个Thread中运行并行执行,内部变量多个线程共享

package CouncurrentDemo;

public class RunnableDemo {

    static class MyRunnable implements Runnable{
        private volatile int count = 10;
        @Override
        public void run() {
            while(count>0){System.out.println("excuting:"+count--);}
        }
    }

    public static void main(String[] args) {
        MyRunnable mythread=new MyRunnable();
        Thread thread1=new Thread(mythread);
        Thread thread2=new Thread(mythread);
        thread1.run();
        thread2.run();
    }
}
//输出
excuting:3
excuting:2
excuting:1

Future

Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果

package CouncurrentDemo;

import java.util.concurrent.*;

public class FutureDemo {
    private ExecutorService executor = Executors.newSingleThreadExecutor();

    public Future<Integer> calculate(Integer inputNumer) {
        return executor.submit(() -> {
            Thread.sleep(1000);
            return inputNumer/2;
        });
    }

    public void demoRun(){
        Future<Integer> future = new FutureDemo().calculate(10);
        while(!future.isDone()) {
            System.out.println("Calculating...");
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


        //阻塞执行:Integer result = future.get();
        //非阻塞版本
        Integer result = null;
        try {
            result = future.get(500, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result);

    }
    
    //多个任务的并行、串行执行
    public void demo2Run(){
        FutureDemo futuredemo=new FutureDemo();
        Future<Integer> future = futuredemo.calculate(10);
        Future<Integer> future2 = futuredemo.calculate(10);
        //此时future是一个线程先1后2,单线程执行
        //todo:只有内部的声明成 private ExecutorService executor = Executors.newFixedThreadPool(2);
        //二者才会并行执行
        while(!future.isDone()&!future2.isDone()) {
            System.out.println("Calculating...");
            try {
                System.out.println(
                        String.format(
                                "future1 is %s and future2 is %s",
                                future.isDone() ? "done" : "not done",
                                future2.isDone() ? "done" : "not done"
                        )
                );
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        int result1 = 0,result2= 0;
        try {
            result1 = future.get();
            result2 = future2.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


        System.out.println(result1 + " and " + result2);

    }
}

相关文章

网友评论

      本文标题:Java 多线程 Runnable、Future、Thread

      本文链接:https://www.haomeiwen.com/subject/bzfblhtx.html