Java Thread suspend()方法

Thread类的suspend()方法使线程无法运行到等待状态。如果要停止线程执行并在发生特定事件时再次启动,则使用此方法。 此方法允许线程暂时停止执行。 可以使用resume()方法恢复挂起的线程。

语法

public final void suspend()

异常

  • SecurityException:如果当前线程无法修改线程。

示例

public class JavaSuspendExp extends Thread  
{    
    public void run()  
    {    
        for(int i=1; i<5; i++)  
        {    
            try  
            {  
                // thread to sleep for 500 milliseconds  
                 sleep(500);  
                 System.out.println(Thread.currentThread().getName());    
            }catch(InterruptedException e){System.out.println(e);}    
            System.out.println(i);    
        }    
    }    
    public static void main(String args[])  
    {    
        // creating three threads   
        JavaSuspendExp t1=new JavaSuspendExp ();    
        JavaSuspendExp t2=new JavaSuspendExp ();   
        JavaSuspendExp t3=new JavaSuspendExp ();   
        // call run() method   
        t1.start();  
        t2.start();  
        // suspend t2 thread   
        t2.suspend();   
        // call run() method   
        t3.start();  
    }    
}

执行上面示例代码,得到以下结果:

Thread-0
1
Thread-2
1
Thread-0
2
Thread-2
2
Thread-0
3
Thread-2
3
Thread-0
4
Thread-2
4

上一篇: Java Runtime类 下一篇:无