最近公司准备使用spark做流式计算,把原来做过的东西拿出来整理一下,有以下内容
1、通过java调用shell脚本启动spark
2、在虚拟机退出时执行特定的方法即注册一个回调函数
对于Runtime类的测试<br/>Every Java application has a single instance of class Runtime
that allows the application to interface with the environment in
which the application is running.
每个java应用程序都有一个RunTime运行时环境的实例,该实例是单例的,它代表着正在运行的应用程序的环境
The current runtime can be obtained from the getRuntime method.
An application cannot create its own instance of this class
当前的运行时环境可以通过getRuntime方法获取,一个运行时环境不能创建自己的运行时环境的实例
package com.lyzx.linux;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class RunTimeTest {
public static void main(String[] args) {
// normalExit();
unNormalExit();
}
/**
* 使用java调用shell脚本,
* //shell脚本内容如下:spark-submit --master spark://master:7077 --class com.lyzx.pi.M /root/package/Pi.jar $1
*
* 使用这个命令来执行shell脚本,如果按照下面的方式就意味着如果spark任务执行1个小时,就要等待一个小时才能获的执行的结果
*
* @throws IOException
* @throws InterruptedException
*/
public static void execShell() throws IOException{
Runtime r = Runtime.getRuntime();
Process p = r.exec("./spark.sh 10000");
try {
int waitFor = p.waitFor();
System.out.println("waitFor:"+waitFor);
} catch (InterruptedException e){
e.printStackTrace();
}
}
/**
* 非正常情况下推出,依然执行回调函数
*/
public static void unNormalExit(){
Thread t = new Thread(new Hook());
Runtime.getRuntime().addShutdownHook(t);
Thread t1 = new Thread(new Th(),"A1");
Thread t2 = new Thread(new Th(),"B1");
t1.start();
//此时主线程奔溃,但是回调函数依然执行
int i = 1/0;
System.out.println("====");
t2.start();
}
/**
* 添加虚拟机结束时的回调函数
* 从下面的例子中可以看出,当4个子线程执行完毕后在执行回调函数
*/
public static void normalExit(){
Thread t = new Thread(new Hook());
Runtime.getRuntime().addShutdownHook(t);
Thread t1 = new Thread(new Th(),"A");
Thread t2 = new Thread(new Th(),"B");
Thread t3 = new Thread(new Th(),"C");
Thread t4 = new Thread(new Th(),"D");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Hook implements Runnable{
@Override
public void run() {
System.out.println("回调函数.....");
}
}
class Th implements Runnable{
@Override
public void run() {
for(int i=0;i<500;i++){
try {
TimeUnit.MILLISECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":::"+i);
}
}
}
本文介绍了如何在Java中利用RunTime类调用shell脚本启动Spark流式计算,同时讲解了如何在虚拟机退出时注册回调函数执行特定任务。
673

被折叠的 条评论
为什么被折叠?



