Originariamente inviato da perzem
Non sono tanto prarico con i thread mi postresti postare una possibile soluzione?? tipo se vorrei stampare lo stato del waitfor finchè nn diventa 0. grazie
Ecco un esempio completo:
codice:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ExecTestFrame extends JFrame implements ActionListener, ExecProcessEvent
{
private JButton button;
private boolean busy;
public ExecTestFrame ()
{
super ("Esempio avvio processo");
setDefaultCloseOperation (JFrame.DO_NOTHING_ON_CLOSE);
setSize (200, 100);
button = new JButton ("Avvia processo");
button.addActionListener (this);
add (button);
addWindowListener (new CloseCheck ());
}
public static void main (String[] args)
{
ExecTestFrame f = new ExecTestFrame ();
f.setVisible (true);
}
public void actionPerformed (ActionEvent e)
{
if (busy)
JOptionPane.showMessageDialog (ExecTestFrame.this, "hai già avviato un processo!");
else
{
ExecProcessThread ept = new ExecProcessThread ("notepad.exe", this);
Thread t = new Thread (ept);
t.start ();
}
}
public void execStarted (String command)
{
busy = true;
}
public void execTerminated (String command, int status)
{
busy = false;
JOptionPane.showMessageDialog (ExecTestFrame.this, "processo terminato con status = " + status);
}
public void execException (String command, Exception e)
{
busy = false;
JOptionPane.showMessageDialog (ExecTestFrame.this, "eccezione " + e);
}
private class CloseCheck extends WindowAdapter
{
public void windowClosing (WindowEvent e)
{
if (ExecTestFrame.this.busy)
JOptionPane.showMessageDialog (ExecTestFrame.this, "processo in esecuzione, non puoi chiudere");
else
System.exit (0);
}
}
}
interface ExecProcessEvent
{
void execStarted (String command);
void execTerminated (String command, int status);
void execException (String command, Exception e);
}
class ExecProcessThread implements Runnable
{
private String command;
private String[] cmdarray;
private ExecProcessEvent epe;
public ExecProcessThread (String command, ExecProcessEvent epe)
{
this.command = command;
this.epe = epe;
}
public ExecProcessThread (String[] cmdarray, ExecProcessEvent epe)
{
this.cmdarray = cmdarray;
this.epe = epe;
}
public void run ()
{
try
{
Runtime r = Runtime.getRuntime ();
Process p = null;
if (command != null)
p = r.exec (command);
else if (cmdarray != null)
p = r.exec (cmdarray);
epe.execStarted (command);
int status = p.waitFor ();
epe.execTerminated (command, status);
}
catch (Exception e)
{
epe.execException (command, e);
}
}
}
Questa applicazione ha un semplice frame che contiene un pulsante. Premendo il pulsante viene avviato Notepad (il blocco note di Windows). Prova ad esempio ad avviare il processo e poi chiuderlo e prova anche a ripremere il pulsante o chiudere il frame se il processo è stato avviato.
Se c'è qualcosa che non ti è chiaro, chiedi pure. Il codice l'ho buttato giù un po' velocemente e magari gli identificativi che ho usato non sono il massimo! E comunque è sicuramente migliorabile!