暂停,恢复和停止在Java中的线程



我正在学习Java中的线程。

以下示例显示了如何暂停,恢复和停止线程:

class MyNewThread implements Runnable {
Thread thrd;
boolean suspended;
boolean stopped;
MyNewThread(String name) {
    thrd = new Thread(this, name);
    suspended = false;
    stopped = false;
    thrd.start();
}
public void run() {
    System.out.println(thrd.getName() + " starting.");
    try {
        for(int i = 0; i<1000; i++) {
            System.out.print(i + " ");
            if(i%10 == 0) {
                System.out.println();
                Thread.sleep(250);
            }
            synchronized(this) {
                while(suspended) {
                    wait();
                }
                if(stopped) break;
            }
        }
    } catch(InterruptedException ex) {
        System.out.println(thrd.getName() + " interrupted.");
    }
    System.out.println(thrd.getName() + " exiting.");
}
synchronized void mystop() {
    stopped = true;
    suspended = false;
    notify();
}
synchronized void mysuspend() {
    suspended = true;
}
synchronized void myresume() {
    suspended = false;
    notify();
}
}
public class Suspend {
public static void main(String[] args) {
    MyNewThread ob1 = new MyNewThread("My Thread");     
    try {
        Thread.sleep(1000);
        ob1.mysuspend();
        System.out.println("Suspending Thread.");
        Thread.sleep(1000);
        ob1.myresume();
        System.out.println("Resuming Thread.");
        Thread.sleep(1000);
        ob1.mysuspend();
        System.out.println("Suspending Thread.");
        Thread.sleep(1000);
        ob1.myresume();
        System.out.println("Resuming Thread.");
        Thread.sleep(1000);
        ob1.mysuspend();
        System.out.println("Stopping Thread.");
        ob1.mystop();
    } catch(InterruptedException ex) {
        System.out.println("Main Thread interrupted.");
    }
    try {
        ob1.thrd.join();
    } catch(InterruptedException ex) {
        System.out.println("Main Thread interrupted.");
    }
    System.out.println("Main Thread exiting.");
}
}

但是这个块:

synchronized(this) {
    while(suspended) {
        wait();
    }
    if(stopped) break;
}

为什么必须指定该块同步?

我知道"同步"来控制线程对共享资源的访问以及如何使用此关键词,但是在示例中,只有2个线程:主线程和OB1线程。主线程不会在MyThread类中输入该同步块或任何同步方法。我只是无法弄清楚原因。

我试图删除"同步"的关键字在块之前。该程序在主线程仍然完成时返回线程"我的线程"中的错误。

要回答您的 direct 问题:您需要在this synchronize ,因为您在this上调用wait()

,为了调用wait((,调用对象wait((的调用线程必须拥有 monitor

so:您需要该同步块(或方法(,以防止以下调用以下呼叫((!

最新更新