在Java小应用程序中如何开启新线程
我使用swing做小应用程序,需要在运行时开启一个线程做监听器,我是这样写的:
public synchronized void listen() {
try {
_transport.listen();
} catch (
IOException ioex) {
System.out.println( "Unable to listen: " + ioex);
System.exit(-1);
}
System.out.println( "Waiting for traps.. ");
try {
this.wait();// Wait for traps to come in
} catch (InterruptedException ex) {
System.out.println( "Interrupted while waiting for traps: " + ex);
System.exit(-1);
}
}
结果程序一运行到这里就不往下走了,整个死掉,请问我该怎样做才能不影响我的程序运行呢?
------解决方案--------------------你要实现一个线程类 然后把监听代码卸载run方法里面
然后启动一个线程实例
看你的代码 就是一个单线程的
------解决方案--------------------Thread thread = new Thread(new Runnable() {
public void run() {
try {
File music = new File(iSystemConstants.muiscfile);
Player player = new Player(new FileInputStream(music));
player.play();
} catch (
FileNotFoundException ex) {
} catch (JavaLayerException ex) {
}
}
});
//thread.start();