大牛们, 好啊
问题如下: 线程A有一个任务, 使用的是单例, 我现在用一个main方法启动A线程, 然后想用另外一个main方法
去终止A线程
A如下:
public class TestThread extends Thread
{
public static TestThread testThread;
private static int initData = 1;
private static boolean isDead = true;
public static boolean isDead()
{
return isDead;
}
private TestThread(){}
public static void setDead(boolean isDead)
{
TestThread.isDead = isDead;
} public static synchronized TestThread getInstance()
{
if (null == testThread)
{
testThread = new TestThread();
}
return testThread;
} @Override
public void run()
{
while (TestThread.isDead())
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("The current value is: " + initData ++);
System.out.println("The thread id is:" +TestThread.getInstance().getId());
}
System.out.println("The thread is stop");
}
public void kill()
{
this.interrupt();
}
}我启动A线程的代码如下:
public class StartThread
{
/**
*
* @param args
*/
public static void main(String[] args)
{
TestThread.getInstance().start();
//TestThread.getInstance().kill();
}
}关闭A线程的类如下:
public class StopThreadTest
{
public static void main(String[] args)
{
TestThread.getInstance().kill();
if (TestThread.getInstance().isInterrupted())
{
System.out.println("关了");
}
else
{
System.out.println("没有关闭");
}
}
}但是为什么总是打印没有关闭啊???
求大牛解决!
问题如下: 线程A有一个任务, 使用的是单例, 我现在用一个main方法启动A线程, 然后想用另外一个main方法
去终止A线程
A如下:
public class TestThread extends Thread
{
public static TestThread testThread;
private static int initData = 1;
private static boolean isDead = true;
public static boolean isDead()
{
return isDead;
}
private TestThread(){}
public static void setDead(boolean isDead)
{
TestThread.isDead = isDead;
} public static synchronized TestThread getInstance()
{
if (null == testThread)
{
testThread = new TestThread();
}
return testThread;
} @Override
public void run()
{
while (TestThread.isDead())
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("The current value is: " + initData ++);
System.out.println("The thread id is:" +TestThread.getInstance().getId());
}
System.out.println("The thread is stop");
}
public void kill()
{
this.interrupt();
}
}我启动A线程的代码如下:
public class StartThread
{
/**
*
* @param args
*/
public static void main(String[] args)
{
TestThread.getInstance().start();
//TestThread.getInstance().kill();
}
}关闭A线程的类如下:
public class StopThreadTest
{
public static void main(String[] args)
{
TestThread.getInstance().kill();
if (TestThread.getInstance().isInterrupted())
{
System.out.println("关了");
}
else
{
System.out.println("没有关闭");
}
}
}但是为什么总是打印没有关闭啊???
求大牛解决!
我觉得你在外部找一个通信标志吧.由线程A去检查这个标志.
比如数据库中的字段,文件,SOCKET等.