zoukankan      html  css  js  c++  java
  • Java的三种多线程

    项目结构

    继承Thread类

    /*
     * Thread类实现了Runnable接口
     */
    
    public class MyThread extends Thread {
        @Override
        public void run() {
            for(int i=0;i<50;i++){
                System.out.println("MyThread子线程 : "+Thread.currentThread().getName()+"~~~"+i);
            }
        }
    }

    实现Runnable接口

    public class MyRunnable implements Runnable {
    
        @Override
        public void run() {
            for(int i=0;i<50;i++){
                System.out.println("MyRunnable子线程 : "+Thread.currentThread().getName()+"~~~"+i);
            }
        }
    
    }

    实现Callable<T>接口

    import java.util.concurrent.Callable;
    /*
     * FutureTask<V>类实现了RunnableFuture<V>接口,
     * RunnableFuture<V>接口实现了Runnable接口、Future<V>接口。
     * FutureTask<V>对象的get方法:等待计算完成,然后获取其结果。
     */
    
    public class MyCallable implements Callable<Integer> {
    
        @Override
        public Integer call() throws Exception {
            int sum = 0;
            for(int i=0;i<100;i++){
                sum += i;
                System.out.println("MyCallable子线程中间结果 : "+sum);
            }
            return sum;
        }
    
    }

    运行

    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.FutureTask;
    
    
    public class Test {
    
        public static void main(String[] args) throws Exception {
            System.out.println("主线程 : "+Thread.currentThread().getName());
            MyThread thread = new MyThread();
            MyRunnable runnable = new MyRunnable();
            Thread thread2 = new Thread(runnable);
            MyCallable callable = new MyCallable();
            FutureTask<Integer> task = new FutureTask<Integer>(callable);
            Thread thread3 = new Thread(task);
            thread.start();
            thread2.start();
            thread3.start();
            int sum = task.get();
            System.out.println("MyCallable子线程最终结果 : " + sum); // 这段代码总是最后执行
        }
    
    }
  • 相关阅读:
    2017.9.29 ubuntu安装mysql服务
    如何在树莓派上安装mjpeg-streamer(针对摄像头为UVC的)
    2016.9.22感想及收获
    GL-iNET路由器如何安装DDNS服务
    2016.7.5 记项目过程中犯的一个从未察觉的低级错误
    C++课程笔记 Lesson 01
    关于Jlink在linux系统下连接错误的解决方法
    如何通过命令提示符进入MySQL服务器
    java面试题
    hive面试题
  • 原文地址:https://www.cnblogs.com/sea-breeze/p/7002622.html
Copyright © 2011-2022 走看看