java 关闭实例_Java中的关闭挂钩的有用示例?

我试图确保我的Java应用程序采取合理的步骤来增强功能,并且其中的一部分涉及正常关闭。我正在阅读有关关机挂钩的信息,但实际上并没有实际使用它们的方法。

有没有实际的例子?

假设我有一个非常简单的应用程序,例如下面的程序,它以100为批号将数字写入文件,将10写入行,并且如果程序被中断,我想确保给定的批处理完成。我知道如何注册一个关闭钩子,但是我不知道如何将其集成到我的应用程序中。有什么建议么?

package com.example.test.concurrency;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.PrintWriter;

public class GracefulShutdownTest1 {

final private int N;

final private File f;

public GracefulShutdownTest1(File f, int N) { this.f=f; this.N = N; }

public void run()

{

PrintWriter pw = null;

try {

FileOutputStream fos = new FileOutputStream(this.f);

pw = new PrintWriter(fos);

for (int i = 0; i < N; ++i)

writeBatch(pw, i);

}

catch (FileNotFoundException e) {

e.printStackTrace();

}

finally

{

pw.close();

}

}

private void writeBatch(PrintWriter pw, int i) {

for (int j = 0; j < 100; ++j)

{

int k = i*100+j;

pw.write(Integer.toString(k));

if ((j+1)%10 == 0)

pw.write('\n');

else

pw.write(' ');

}

}

static public void main(String[] args)

{

if (args.length < 2)

{

System.out.println("args = [file] [N] "

+"where file = output filename, N=batch count");

}

else

{

new GracefulShutdownTest1(

new File(args[0]),

Integer.parseInt(args[1])

).run();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值