我是Java的初学者。我想通过生成一个Thread来实现一个Timer。我想要运行的方式是主线程即使在产生线程后也应该继续工作。但是一旦线程完成Task,它应该通知主线程任务完成。我查看了Thread.join()和Thread.sleep()。对于这两种方法,主线程等待线程完成任务。但是我希望主线程继续运行。
我在下面编写了一个代码,主线程调用一个线程,线程执行任务10秒。但是我无法通知主线程有关任务完成的信息。 请帮助我。
public class MainThreadtest {
public static void main(String[] args) {
dispthread2 dt2 = new dispthread2();
dt2.start();
System.out.println("Thread dt2 has started");
}
}
第二课
public class dispthread2 extends Thread {
public void run() {
long endTimemillis = System.currentTimeMillis() + 10000;
while (System.currentTimeMillis() < endTimemillis) {
}
System.out.println("The task is done");
}
}
答案 0 :(得分:1)
解决此问题的一种方法是不需要使用Thread#join,从而允许两个线程独立运行:
例如:
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.event.SwingPropertyChangeSupport;
public class MainThreadTest {
public static void main(String[] args) {
DispThread2 dt2 = new DispThread2();
dt2.addPropertyChangeListener(DispThread2.STATE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("DT2 Thread state (from Main Thread): " + evt.getNewValue());
if (evt.getNewValue() == DispThreadState.DONE) {
System.out.println("Thread dt2 is now done (from Main Thread)");
}
}
});
new Thread(dt2, "DT2").start();
System.out.println("Thread dt2 has started");
}
}
class DispThread2 implements Runnable {
public static final String STATE = "state";
private volatile DispThreadState state = DispThreadState.PENDING;
private PropertyChangeSupport support = new SwingPropertyChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener listener) {
support.addPropertyChangeListener(listener);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
support.addPropertyChangeListener(propertyName, listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
support.removePropertyChangeListener(listener);
}
public void run() {
setState(DispThreadState.RUNNING);
long endTimemillis = System.currentTimeMillis() + 10000;
while (System.currentTimeMillis() < endTimemillis) {
}
System.out.println("The task is done");
setState(DispThreadState.DONE);
}
public DispThreadState getState() {
return state;
}
public void setState(DispThreadState state) {
DispThreadState oldValue = this.state;
DispThreadState newValue = state;
this.state = state;
support.firePropertyChange(STATE, oldValue, newValue);
}
}
enum DispThreadState {
PENDING, RUNNING, DONE
}