Java模拟音乐播放器 暂停与重新播放——线程如何控制另外一个线程的状态

package com.example.Thread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 模拟播放器 暂停/播放
 *
 * 启动后先输入1 执行播放功能会造成死锁
 *  原因在于run持有锁 restart获取锁时 run没有释放
 * Created by 达达队长 on 2018/4/27.
 */

class MyThread implements Runnable {
    private volatile boolean isSuspend = false;
    private volatile int i = 0;

    @Override
    public void run() {
        synchronized (this) {
            try {
                while (true) {
                    if (isSuspend) {
                        wait();
                    } else {
                        Thread.sleep(1000);

                        System.out.println("I am running i=" + i++);
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    // 0
    public void suspend() {
        isSuspend = true;
        System.out.println("暂停");
    }

    // 1
    public synchronized void restart() {
        isSuspend = false;
        notify();
        System.out.println("启动");
    }
}

public class SuspendAndRestart {

    public static void main(String[] args) throws IOException {
        MyThread my = new MyThread();
        Thread thread = new Thread(my);
        thread.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line = "";
        while (!"exit".equals(line = reader.readLine())) {
            if (line.equals("1")) {
                my.restart();
            } else if (line.equals("0")) {
                my.suspend();
            }
            System.out.println("System in :::" + line);
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/Yiran583/p/8961497.html