Java simulates music player pause and replay - how a thread controls the state of another thread

package com.example.Thread;

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

/**
 * Simulate player pause/play
 *
 * Input 1 to execute the play function after startup will cause deadlock
 * The reason is that run does not release the lock when run holds the lock and restart acquires the lock
 * Created by Captain Dada 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( "Pause" );
    }

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

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);
        }
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325005681&siteId=291194637