suspend.java

来自「由于想一次上传成功 所以将二个教程打包成了一个 这些例子几乎包含了所有java的」· Java 代码 · 共 60 行

JAVA
60
字号
class CustomThread extends Thread 
{
    volatile boolean goFlag = true;
    
    CustomThread(String name) 
    {
        super(name);
        start(); 
    }

    public void run() 
    {
        try {
            for(int loop_index = 0; loop_index <= 5; loop_index++) {
                System.out.println(Thread.currentThread().getName() + " here...");
                Thread.sleep(500);
                synchronized(this) {
                    while(!goFlag) {
                        wait();
                    }
                }
            }
        } catch (InterruptedException e) {}
    }

    public void newSuspend() 
    {
        goFlag = false;
    }

    synchronized public void newResume() 
    {
        goFlag = true;
        notify();
    }
}

class suspend 
{
    public static void main(String args[]) 
    {
        CustomThread thread1 = new CustomThread("one");
        CustomThread thread2 = new CustomThread("two");

        try {
            Thread.sleep(1000);
            System.out.println("Suspending thread one...");
            thread1.newSuspend();
            Thread.sleep(1000);
            System.out.println("Resuming thread one...");
            thread1.newResume();
        } catch (InterruptedException e) {}

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {}
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?