我有一个Java小程序。该applet中的一个类正在创建一个线程来完成一些工作,等待30秒完成该工作,如果该工作在30秒内没有完成,它将设置一个布尔值来停止该线程。等待和布尔变化是同步的块,这是必要的考虑没有从这些2在这里同步需要
System.out.println("Begin Start Session");
_sessionThread = new SessionThread();
_sessionThread.start();
synchronized (_sessionThread)
{
_sessionThread.wait(30000);
_sessionThread._stopStartSession = true;
}
一边跑,为什么我不能只是这样做,而不是没有其他线程。
System.out.println("Begin Start Session");
_sessionThread = new SessionThread();
_sessionThread.start();
_sessionThread.wait(30000);
_sessionThread._stopStartSession = true;
SessionThread运行方法。调用一个JNI方法来调用一个dll来打开一个程序窗口。
public void run()
{
try
{
startExtraSession();
}
catch (Throwable t)
{
t.printStackTrace();
}
notify();
}
private native void openSessionWindow(String session_file);
private void startExtraSession()
{
final String method_name = "startExtraSession";
String title = _sessionInfo._title;
long hwnd = 0;
openSessionWindow(_sessionInfo._configFile);
try
{
//Look for a window with the predefined title name...
while ((hwnd = nativeFindWindow(title)) == 0 && !_stopStartSession)
{
Thread.sleep(500);
}
}
catch(Throwable t)
{
t.printStackTrace();
}
}
1.是否真的需要同步?
2.除了使用线程之外,还有更好的方法来完成这个吗?
如果线程由班级拥有,他将从中调用同步部分,是否不符合此要求?自从我的Java时代已经很长时间了,所以请赐教。 – 2009-12-03 20:21:31
如果您在任何同步方法或任何同步块之外,则您不拥有任何监视器,因此无法调用“wait”。让我编辑我的答案在锁定/监视器采集上更清晰一些。 – Romain 2009-12-04 08:12:46