zoukankan      html  css  js  c++  java
  • java创建多线程实现并行计算任务处理

    1、直接上代码一看明白:

    package multithreadingTest;
    
    class fblib extends Thread{
    
        public static Integer fb(Integer n){
            return n<2?1:fb(n-1)+fb(n-2);
        }
    
        public static void bl1(int n) throws InterruptedException {
            for (int i=0;i<n;i++){
                System.out.println("fblib:"+i);
                Thread.sleep(500);
            }
        }
    
        @Override
        public void run() {
            super.run();
            try {
                bl1(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //System.out.println(fb(40));
        }
    }
    
    class countl extends Thread{
        public static void bl(int n) throws InterruptedException {
            for (int i=0;i<n;i++){
                System.out.println("count1:"+i);
                Thread.sleep(500);
            }
        }
    
        @Override
        public void run() {
            super.run();
            try {
                bl(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    public class mutithDemo{
        public  mutithDemo(){}
        public static void main(String[] args) throws InterruptedException {
    
            // 1、不采用多线程进行并发执行
            System.out.println("-----不采用多线程执行任务---------");
            long startTime = System.currentTimeMillis();
            fblib.bl1(10);
            countl.bl(10);
            long endTime = System.currentTimeMillis();
            System.out.println(endTime-startTime);
    
            // 2、采用多线进行并发任务执行
            System.out.println("-----采用多线程执行任务实现并发---------");
            long startTime1 = System.currentTimeMillis();
            fblib f1 = new fblib();
            countl f2 = new countl();
            //开启两个线程执行两个任务
            f1.start();
            f2.start();
            //等待这两个线程执行结束后在执行以下代码。
            f1.join();
            f2.join();
    
            long endTime1 = System.currentTimeMillis();
            System.out.println(endTime1-startTime1);
    
        }
    }
    

      

  • 相关阅读:
    sklearn 的 metrics
    转载:spring boot 中使用 jpa以及jpa介绍
    springboot 事件监听(@EventListener实现)
    多线程:创建线程和线程的常用方法
    缓存穿透、缓存击穿、缓存雪崩区别和解决方案
    不定义新变量,交换两个变量的值
    理解WebSocket心跳及重连机制
    SpringBoot实现WebSocket
    批量打包成ZIP压缩文件
    RocketMQ入门教程
  • 原文地址:https://www.cnblogs.com/wuzaipei/p/11173283.html
Copyright © 2011-2022 走看看