【发布时间】:2009-12-03 20:06:57
【问题描述】:
我有一个 java 小程序。该小程序中的一个类正在创建一个线程来完成一些工作,等待 30 秒以完成该工作,如果它在 30 秒内未完成,它会设置一个布尔值来停止线程。等待和布尔更改在一个同步块中,考虑到除了这两个之外没有其他线程在运行,这是必要的吗。
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 synchronization multithreading