内部线程

来源:互联网 发布:mac好用的翻墙软件 编辑:程序博客网 时间:2024/04/28 12:31

public class SelfRun implements Runnable
{
    private Thread internalThread;
    private volatile boolean noStopRequested;
    public SelfRun()
    {
        System.out.println( "in constructor - initializing..." );
        noStopRequested = true;
        internalThread = new Thread( this );
        internalThread.start();
    }

    public static void main(String[] args)
    {
        SelfRun sr = new SelfRun();
        try
        {
            Thread.sleep( 3000 );
        }catch( InterruptedException x )
        {
           
        }
        sr.stopRequest();
    }

    public void run()
    {
        if( Thread.currentThread()!=internalThread )
        {
            throw new RuntimeException( "only the internal " +
                   "thread is allowed to invoke run()" );
        }
        while( noStopRequested )
        {
            System.out.println( "in run() - still going..." );
            try
            {
                Thread.sleep( 700 );
            }catch( InterruptedException x )
            {
                Thread.currentThread().interrupt();
            }
        }
    }
    public void stopRequest()
    {
        noStopRequested = false;
        internalThread.interrupt();
    }
    public boolean isAlive()
    {
        return internalThread.isAlive();
    }
}
///////////////////////////////////////////////////////////////////

in constructor - initializing...
in run() - still going...
in run() - still going...
in run() - still going...
in run() - still going...
in run() - still going...

原创粉丝点击