我似乎找不到这个问题的答案。我所拥有的是以下内容,我有一个活动,它产生 8 个线程来做某些事情,这些线程需要在活动关闭并且有效时保持活动状态。我遇到的问题是,当我再次打开活动时,它会产生同一线程的另一个实例。
我在 Eclipse 中使用 DDMS 来验证是否正在生成线程的多个副本,我还有一条 toast 消息,每秒输出线程的 ID,以验证确实有两个线程副本在运行。
所以我的问题是,如何避免线程的多个实例运行或如何杀死旧实例?
下面是其中一个线程的示例。
new Thread(new Runnable()
{
public void run()
{
while(true)
{
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); // This is where we read the global date and time into our string
currentDateTimeString = df.format(new Date());
DateFormat womm = new SimpleDateFormat("mm"); // This is where we read the minute of the wait one minute into our string
WOMMinString = womm.format(new Date());
DateFormat womh = new SimpleDateFormat("hh"); // This is where we read the hour of the wait one minute into our string
WOMHourString = womh.format(new Date());
DateFormat cds = new SimpleDateFormat("dd"); // This is where we read the current day into our string
currentDayString = cds.format(new Date());
DateFormat cms = new SimpleDateFormat("MM"); // This is where we read the current month into our string
currentMonthString = cms.format(new Date());
DateFormat cys = new SimpleDateFormat("yyyy"); // This is where we read the current year into our string
currentYearString = cys.format(new Date());
try
{
Thread.sleep(1000);
}
catch (InterruptedException e1)
{
appendLog("Could not sleep the thread (Main 2) " + currentDateTimeString + "");
}
}
}
}).start();
谢谢。