javafutures的简单介绍

博主:adminadmin 2022-12-24 02:51:06 58

本篇文章给大家谈谈javafutures,以及对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

如何取消已经执行的scheduledexecutorservice.scheduleatfixedrate

java中的定时器功能

在jdk1.5之前,大家都用传统的定时器Timer来实现该功能

如,我们需要定制一个特殊方法,在程序首次载入时就执行,以后每隔一定的时间去执行那个方法

传统的做法如下;

[html] view plain copy

/**

* 定时器的测试(传统方式)

*/

public static void testTimer(){

Timer timer = new Timer();

TimerTask task = new TimerTask() {

@Override

public void run() {

System.out.println("Timer:测试开始!");

}

};

//第一个参数是要执行的任务

//第二个是程序启动后要延迟多长后执行,单位毫秒

//第三个参数是,第一次执行后,以后每隔多长时间后在行

timer.schedule(task, 5000, 3000);

}

jdk1.5出来后,我们就可以改变这种做法,换种方式

如代码:

[html] view plain copy

/**

* 定时器的测试(ScheduledExecutorService)

*/

public static void testExcuters(){

ScheduledExecutorService service = Executors.newScheduledThreadPool(1);

service.scheduleAtFixedRate(new Runnable() {

@Override

public void run() {

System.out.println("ScheduledExecutorService:测试开始");

}

}, 5, 3,TimeUnit.SECONDS);

}

java 导出问题

导出excel的话,你可以使POI组件,

public static void evaluatingExcel() throws Exception{

//创建excel工作簿

HSSFWorkbook workbook = new HSSFWorkbook();

//设置标题样式

HSSFCellStyle cs = workbook.createCellStyle();

cs.setAlignment(HSSFCellStyle.ALIGN_CENTER); //左右居中

cs.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //上下居中

// 在Excel工作簿中建一工作表,其名为缺省值

// 如要新建一名为"效益指标"的工作表,其语句为:

HSSFSheet sheet = workbook.createSheet("汇总打印");

// HSSFSheet sheet = workbook.createSheet();

// 在索引0的位置创建行(最顶端的行)

HSSFRow row = sheet.createRow((short)0);

// 在索引0的位置创建单元格(左上端)

HSSFCell cell = row.createCell(0);

// 定义单元格为字符串类型

cell.setCellType(HSSFCell.CELL_TYPE_STRING);

// 在单元格中输入一些内容

cell.setCellValue("姓名");

cell.setCellStyle(cs);

//创建第二个单元格

cell = row.createCell(1);

cell.setCellValue("客观评分");

cell.setCellStyle(cs);

cell = row.createCell(2);

cell.setCellValue("客观评分");

cell.setCellStyle(cs);

cell = row.createCell(3);

cell.setCellValue("主观评分");

cell.setCellStyle(cs);

cell = row.createCell(4);

cell.setCellValue("主观评分");

cell.setCellStyle(cs);

cell = row.createCell(5);

cell.setCellValue("主观评分");

cell.setCellStyle(cs);

cell = row.createCell(6);

cell.setCellValue("级别");

cell.setCellStyle(cs);

// 在索引1的位置创建行(最顶端的行)

HSSFRow row2 = sheet.createRow(1);

// 在索引0的位置创建单元格(左上端)

HSSFCell cell2 = row2.createCell(0);

//// 定义单元格为字符串类型

// cell2.setCellType(HSSFCell.CELL_TYPE_STRING);

//// 在单元格中输入一些内容

// cell2.setCellValue("姓名");

//创建第二个单元格

cell2 = row2.createCell(1);

cell2.setCellValue("客观评分");

cell2 = row2.createCell(2);

cell2.setCellValue("客观评分");

cell2 = row2.createCell(3);

cell2.setCellValue("主观评分");

cell2 = row2.createCell(4);

cell2.setCellValue("主观评分");

cell2 = row2.createCell(5);

cell2.setCellValue("主观评分");

cell2 = row2.createCell(6);

cell2.setCellValue("级别");

//合并单元格

// sheet.addMergedRegion(new CellRangeAddress(0,0,1,3));//合并第0行的第1单元格和第3单元格,相当于,合并1,2,3单元格

// sheet.addMergedRegion(new Region(0,(short)1,0,(short)2));//合并第0行的第1单元格和第2单元格

// sheet.addMergedRegion(new Region(0,(short)2,0,(short)3));//合并第0行的第1单元格和第3单元格,相当于,合并1,2,3单元格

//sheet.setColumnWidth(5,400);//设置该工作区的第5列的宽度为400像素

sheet.addMergedRegion(new CellRangeAddress(0,1,0,0));//合并第一,二行的第一列

sheet.addMergedRegion(new CellRangeAddress(0,1,6,6));//合并第一,二行的第六列

sheet.addMergedRegion(new CellRangeAddress(0,0,1,2));//合并第一行的第1单元格和第二单元格

sheet.addMergedRegion(new CellRangeAddress(0,0,3,5));//合并第一行的第1单元格和第二单元格

// 新建一输出文件流

FileOutputStream fOut = new FileOutputStream(fileUrl);

// 把相应的Excel 工作簿存盘

workbook.write(fOut);

fOut.flush();

// 操作结束,关闭文件

fOut.close();

System.out.println("文件生成...");

}

java 如何实现等待子线程结束

有多种实现方式,下面列出两种。

第一种:实现Callable类,使用有返回值的线程,只有线程执行完成后才会返回结果。

import java.util.ArrayList;

import java.util.List;

import java.util.Random;

import java.util.concurrent.*;

public class Main {

    // 初始化一个容量为10的线程池

    static final ExecutorService pool = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ListFutureString futures = new ArrayList();

        for (int i = 0; i  3; i++) {

            MyThread thread = new MyThread("线程" + i);

            futures.add(pool.submit(thread));

        }

        for (FutureString future : futures) {

            String name = future.get();

            System.out.println(name + "执行完成...");

        }

        System.out.println("所有线程执行完成!");

    }

}

class MyThread implements CallableString {

    private String name;

    public MyThread(String name) {

        this.name = name;

    }

    @Override

    public String call() throws Exception {

        // TODO 执行业务

        // 随机延迟,模拟线程耗时

        Thread.sleep(1000 + new Random().nextInt(2000));

        return name;

    }

}

第二种:使用CountDownLatch实现线程计数,代码如下:

import java.util.Random;

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class Main2 {

    // 初始化一个容量为10的线程池

    static final ExecutorService pool = Executors.newFixedThreadPool(10);

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

        int threadCount = 3;

        // 初始化CountDownLatch,用于线程计数

        CountDownLatch latch = new CountDownLatch(threadCount);

        for (int i = 0; i  threadCount; i++) {

            MyThread thread = new MyThread("线程" + i, latch);

            pool.execute(thread);

        }

        // 阻塞当前线程,CountDownLatch计数减为0时表示所有线程都执行完毕,才会释放主线程的阻塞

        latch.await();

        System.out.println("所有线程执行完成!");

    }

}

class MyThread implements Runnable {

    private String name;

    private CountDownLatch latch;

    public MyThread(String name, CountDownLatch latch) {

        this.name = name;

        this.latch = latch;

    }

    @Override

    public void run() {

        // TODO 执行业务

        // 随机延迟,模拟线程耗时

        try {

            Thread.sleep(1000 + new Random().nextInt(2000));

        } catch (InterruptedException e) {

        }

        // 计数减一

        latch.countDown();

        System.out.println(name + "执行完毕...");

    }

}

java中怎样得到线程结束的通知?

使用 Google Guava 提供的 ListeningExecutorService 启动线程会返回一个 ListenableFuture?,然后实现它的执行完的回调接口,就可以监听线程完成的状态,如下代码:

ListenableFutureXX future = null;

Futures.addCallback(future,

     new FutureCallbackXX {

       public void onSuccess(XX result) {//线程执行完的回调接口

         xx(result);

       }

       public void onFailure(Throwable t) {//线程执行失败的回调接口

         reportError(t);

       }

     });

java并发编程学习:如何等待多个线程执行完成

实现方式多种多样,下面列两种供参考:

import java.util.ArrayList;

import java.util.List;

import java.util.concurrent.*;

public class Main {

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        System.out.println("方式1");

        System.out.println("================================================");

        // 方式1

        // 创建一个线程池,并创建10个线程放入线程池执行

        ExecutorService pool = Executors.newCachedThreadPool();

        for (int i = 0; i  10; i++) {

            pool.execute(new MyThread("线程" + i));

        }

        // 线程池不再接收新任务

        pool.shutdown();

        // 线程池中的所有线程都执行完pool.isTerminated()才返回true

        while (!pool.isTerminated()) {

            Thread.sleep(100);

        }

        System.out.println("所有线程执行完成");

        System.out.println("\n\n方式2");

        System.out.println("================================================");

        // 方式2

        ExecutorService pool2 = Executors.newCachedThreadPool();

        ListFuture futures = new ArrayList();

        for (int i = 0; i  10; i++) {

            // 使用实现Callable接口的方式创建线程,通过Future可以获取线程中返回的结果

            Future future = pool2.submit(new MyThread2("线程" + i));

            futures.add(future);

        }

        for (Future future : futures) {

            // 该方法会阻塞主线程,直到线程执行完成

            future.get();

        }

        System.out.println("所有线程执行完成");

    }

}

class MyThread extends Thread {

    private String name;

    public MyThread(String name) {

        this.name = name;

    }

    @Override

    public void run() {

        try {

            Thread.sleep(3000);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println(name + "执行完成");

    }

}

class MyThread2 implements Callable {

    private String name;

    public MyThread2(String name) {

        this.name = name;

    }

    @Override

    public Object call() throws Exception {

        try {

            Thread.sleep(3000);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println(name + "执行完成");

        return null;

    }

}

javafutures的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于、javafutures的信息别忘了在本站进行查找喔。

The End

发布于:2022-12-24,除非注明,否则均为首码项目网原创文章,转载请注明出处。