⑴ java suspend()的问题
suspend()该方法在jdk1.6中已经不推荐使用了,过时了。如果是非阻塞线程只加①句,“使用一个共享变量,线程周期性检测这一变量的值”。如果线程被阻塞,它便不能核查共享变量,也就不能停止。因此不加①只加②即可实现。
class A extends Thread
{
volatile boolean stop = false;
static class B
{
public void () throws Exception
{
A thread = new A();
System.out.println("Starting thread...");
thread.start();
Thread.sleep(3000);
System.out.println("Asking thread to stop...");
thread.stop = true; // ①
thread.interrupt(); // ②
Thread.sleep(3000);
System.out.println("Stopping application...");
// System.exit( 0 );
}
}
public void run()
{
while (!stop)
{
System.out.println("Thread running...");
try
{
Thread.sleep(1000); // 模拟线程被阻塞
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted...");
}
}
System.out.println("Thread exiting under request...");
}
}
⑵ java程序运行过程中如何暂停,恢复
java控制程序执行,使用的是Thread这个类,可以控制程序暂停或者休眠几秒再执行。示例如下:
{
privatebooleansuspend=false;
privateStringcontrol="";//只是需要一个对象而已,这个对象没有实际意义
publicvoidsetSuspend(booleansuspend){
if(!suspend){
synchronized(control){
control.notifyAll();
}
}
this.suspend=suspend;
}
publicbooleanisSuspend(){
returnthis.suspend;
}
publicvoidrun(){
while(true){
synchronized(control){
if(suspend){
try{
control.wait();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
this.runPersonelLogic();
}
}
();
publicstaticvoidmain(String[]args)throwsException{
MyThreadmyThread=newMyThread(){
protectedvoidrunPersonelLogic(){
System.out.println("myTheadisrunning");
}
};
myThread.start();
Thread.sleep(3000);
myThread.setSuspend(true);
System.out.println("myThreadhasstopped");
Thread.sleep(3000);
myThread.setSuspend(false);
}
}
⑶ 我爱学Java之Thread中stop,suspend,resume为什么不安全
当调用stop()方法时会发生两件事:
1.即刻停止run()方法中剩余的全部工作,包括在catch或finally语句中,并抛出ThreadDeath异常(通常情况下此异常不需要显示的捕获),因此可能会导致一些清理性的工作的得不到完成,如文件,数据库等的关闭。
2.会立即释放该线程所持有的所有的锁,导致数据得不到同步的处理,出现数据不一致的问题。
suspend()和resume()必须要成对出现,否则非常容易发生死锁。
因为suspend方法并不会释放锁,如果使用suspend的目标线程对一个重要的系统资源持有锁,那么没任何线程可以使用这个资源直到要suspend的目标线程被resumed,如果一个线程在resume目标线程之前尝试持有这个重要的系统资源锁再去resume目标线程,这两条线程就相互死锁了,也就冻结线程。
⑷ Java多线程调试如何完成信息输出处理
默认情况下,在调试多线程程序时,当遇到断点时(breakpoint),当前线程暂停,而其它线程继续运行,有些情况下,这是我们不想要看到的。比如下面的例子:
再调试多线程程序:
可以看到所有线程都Suspend了。