编程语言
首页 > 编程语言> > Java线程的暂停(suspend)和恢复(resume)

Java线程的暂停(suspend)和恢复(resume)

作者:互联网

package org.example.thread;

public class SuspendAndResumeThread extends Thread {
    private long count = 0;

    public long getCount() {
        return count;
    }

    public void setCount(long count) {
        this.count = count;
    }

    @Override
    public void run() {
        while (true) {
            count++;
        }
    }
}
package org.example.thread;

public class SuspendAndResumeThreadDemo {
    public static void main(String[] args) {
        try {
            SuspendAndResumeThread thread = new SuspendAndResumeThread();
            thread.start();
            Thread.sleep(5000);

            // work1
            thread.suspend();
            System.out.println("暂停");
            System.out.println("work1= " + System.currentTimeMillis() + " count=" + thread.getCount());
            Thread.sleep(5000);
            System.out.println("work1= " + System.currentTimeMillis() + " count=" + thread.getCount());
            thread.resume();
            System.out.println("恢复");
            Thread.sleep(5000);

            // work2
            thread.suspend();
            System.out.println("暂停");
            System.out.println("work2= " + System.currentTimeMillis() + " count=" + thread.getCount());
            Thread.sleep(5000);
            System.out.println("work2= " + System.currentTimeMillis() + " count=" + thread.getCount());
            thread.resume();
            System.out.println("恢复");
            Thread.sleep(5000);

            // work3
            thread.suspend();
            System.out.println("暂停");
            System.out.println("work3= " + System.currentTimeMillis() + " count=" + thread.getCount());
            Thread.sleep(5000);
            System.out.println("work3= " + System.currentTimeMillis() + " count=" + thread.getCount());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

标签:count,suspend,Java,Thread,thread,resume,System,println,out
来源: https://blog.csdn.net/jake_Aaron/article/details/120140912