java进程之间通信

一 进程间通信的方法主要有以下几种:

  (1)管道(Pipe):管道可用于具有亲缘关系进程间的通信,允许一个进程和另一个与它有共同祖先的进程之间进行通信。
  (2)命名管道(named pipe):命名管道克服了管道没有名字的限制,因此,除具有管道所具有的功能外,它还允许无亲缘关 系 进程间的通信。命名管道在文件系统中有对应的文件名。命名管道通过命令mkfifo或系统调用mkfifo来创建。
  (3)信号(Signal):信号是比较复杂的通信方式,用于通知接受进程有某种事件发生,除了用于进程间通信外,进程还可以发送 信号给进程本身;linux除了支持Unix早期信号语义函数sigal外,还支持语义符合Posix.1标准的信号函数sigaction(实际上,该函数是基于BSD的,BSD为了实现可靠信号机制,又能够统一对外接口,用sigaction函数重新实现了signal函数)。
(4)消息(Message)队列:消息队列是消息的链接表,包括Posix消息队列system V消息队列。有足够权限的进程可以向队列中添加消息,被赋予读权限的进程则可以读走队列中的消息。消息队列克服了信号承载信息量少,管道只能承载无格式字节流以及缓冲区大小受限等缺
  (5)共享内存:使得多个进程可以访问同一块内存空间,是最快的可用IPC形式。是针对其他通信机制运行效率较低而设计的。往往与其它通信机制,如信号量结合使用,来达到进程间的同步及互斥。
  (6)内存映射(mapped memory):内存映射允许任何多个进程间通信,每一个使用该机制的进程通过把一个共享的文件映射到自己的进程地址空间来实现它。
  (7)信号量(semaphore):主要作为进程间以及同一进程不同线程之间的同步手段。
  (8)套接口(Socket):更为一般的进程间通信机制,可用于不同机器之间的进程间通信。起初是由Unix系统的BSD分支开发出来的,但现在一般可以移植到其它类Unix系统上:Linux和System V的变种都支持套接字。

二 .而在java中我们实现多线程间通信则主要采用"共享变量"和"管道流"这两种方法

(1) 通过访问共享变量的方式(注:需要处理同步问题)

(2)通过管道流方式实现,也就是该文章下面的内容

三.调用方代码如下

package com.ljm.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.*;

/**
 * @Description  通过进程方式调用并获取返回结果
 * @Author lijunming
 * @Date 2019/8/8 16:15
 **/
public class Test implements Callable<String> {

    //任务队列
    static Queue<String> queue = new LinkedList<String>();

    public String call() throws Exception {
        String osname = System.getProperty("os.name").toLowerCase();
        String line = null;
        StringBuilder sb = new StringBuilder();
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        try {
            //根据系统环境执行对应的脚本
            if (osname.indexOf("linux") != -1) {
                String[] cmdA = {"/bin/sh", "-c", "java -jar /test/test.jar " + queue.poll()};
                process = Runtime.getRuntime().exec(cmdA);
            } else {
                String command = "java -jar D:\\test.jar " + queue.poll();
                process = runtime.exec(command);
            }
            BufferedReader bufferedReader = new BufferedReader
                    (new InputStreamReader(process.getInputStream(), "GBK"));
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line + "\n");
            }
            //等待子进程处理任务结束
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            process.destroy();
        }
        return sb.toString();
    }


    public static void main(String[] args) throws Exception {
        String osname = System.getProperty("os.name").toLowerCase();
        if (osname.contains("window")) {
            queue.offer("d:/test/15.jpg");
            queue.offer("d:/test/b1.jpg");
            queue.offer("d:/test/17.jpg");
        } else {
            queue.offer("/test/15.jpg");
            queue.offer("/test/16.jpg");
            queue.offer("/test/17.jpg");
        }
        ExecutorService executor = Executors.newSingleThreadExecutor();
        //同步获取执行结果
        Future<String> results = executor.submit(new Test());
        Future<String> results1 = executor.submit(new Test());
        Future<String> results2 = executor.submit(new Test());
        String a = results.get();
        String b = results1.get(1, TimeUnit.MINUTES);//设置任务超时时间为1分钟
        String c = results2.get();
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        executor.shutdown();
    }
}

四.被调用方

package com.ljm.test;


import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * 通过outputStream把执行结果返回父进程
 */
public class TestProcess {


    public static void main(String[] args) {
        String picPath=args[0]; //调用方传递的参数
        FileInputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        String fileName = null;
        String osname = System.getProperty("os.name").toLowerCase();
        if (osname.contains("linux")) {
            fileName = "/tmp/" + System.currentTimeMillis() + Math.random();
        } else {
            fileName = "D:/" + System.currentTimeMillis() + Math.random();
        }
        String result = "需要返回的执行结果";
        try {
            fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(result.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
             //删除作为管道流用的文件
            new File(fileName).delete();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/ming19951224/article/details/100506116