java learning: a multi-threaded - and stop blocking method thread

1, the thread stop

There are two ways to stop the thread, and naturally stop outside interference.
(1) natural stop: Normal finished thread body.
(2) External Interference: Thread class is defined using the identification thread body; body using the thread identifier; provides method for changing the external identifier; external conditions according to the method is called. As shown in the following code defines stop control thread identification flag.

public class test {

	public static void main(String[] args) {

		Play py = new Play();
		new Thread(py).start();
		try {
			for (int i = 0; i < 100; i++) {
				System.out.println("i的值是  " + i);
				if (i == 50) {
					py.stop();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class Play implements Runnable {
	private boolean flag = true;

	@Override
	public void run() {
		while (flag) {
			System.out.println("Play Thread is running---------");
		}
	}

	public void stop() {
		this.flag = false;

	}
}

2, blocking thread

(1) join (): merged threads, the original thread to block.

After the calling thread is to let the meaning of the method is complete run () method, the code (after) then perform join. That is, to let two threads merge, to achieve synchronization.

(2) sleep (): Specifies the sleep time, do not release the lock.

Thread designated sleep time, sleep. We will take the initiative to let the CPU, after a specified period of time, enter the ready state, waiting for the CPU to allocate this thread to continue. In this process, it will not release the lock. (Holding objects to sleep, do not release the lock)

(3) yield (): This thread is suspended, waiting for CPU scheduling.

And sleep () is not different from the specified time, directly into the ready state, so there are likely to be scheduled directly into operation.

Published 57 original articles · won praise 13 · views 1095

Guess you like

Origin blog.csdn.net/weixin_42924812/article/details/105233988