【发布时间】:2014-02-06 00:38:02
【问题描述】:
我正在尝试编写一个程序,首先 ssh'es 到两台不同的机器,然后对它们执行一些 http 请求。这意味着为了能够执行我的 http 请求,ssh 隧道应该运行。
我所做的是我有两个线程,每个线程都运行 ssh 命令到其中一个框:
Thread thread1 = new Thread(new Runnable(){
public void run(){
try{
Process p1 = Runtime.getRuntime().exec("ssh -A -L12345:localhost:54321 firsthost.com");
p1.waitFor();
}catch (Exception e){}
}
}) ;
thread1.start();
Thread thread2 = new Thread(new Runnable(){
public void run(){
try{
Process p2 = Runtime.getRuntime().exec("ssh -A -L12345:localhost:54321 secondhost.com");
p2.waitFor();
}catch (Exception e){}
}
}) ;
thread2.start();
现在的问题是,在启动线程后,它们并不总是立即开始运行,这意味着我会在建立连接之前发送我的请求。有没有一种简单的方法(不使用锁或互斥锁)可以确保我只在线程启动后才返回主程序? (我当然不想等待它们结束,因为它们永远不会结束。只需运行第一个命令一次 :) 此外,如果有更好的方法在后台运行进程而不是让这两个单独的线程,那也会很棒!)
谢谢!
【问题讨论】:
标签: java multithreading ssh