wait code demonstrates thread, notify method

package com.dq;

public class ThreadTest implements Runnable
{
	public static Object lock = new Object();
	@Override
	public void run() 
	{
		System.out.println("进入线程执行体,当前线程名: " + Thread.currentThread().getName());
		synchronized (lock) 
		{
			System.out.println("进入同步代码块,当前线程名: " + Thread.currentThread().getName());
			try 
			{
				if (Thread.currentThread().getName().equals("thread1")) 
				{
					System.out.println(Thread.currentThread().getName() + "线程进入等待状态,释放同步锁");
					lock.wait();
				}
				if (Thread.currentThread().getName().equals("thread2")) 
				{
					lock.notify();
				}
			} 
			catch (Exception e) 
			{
				System.out.println("exception");
			}
			System.out.println("走出同步代码块,当前线程名: " + Thread.currentThread().getName());
		}
		System.out.println("走出线程执行体,当前线程名: " + Thread.currentThread().getName());
	}
	
	public static void main(String[] args) throws InterruptedException 
	{
		ThreadTest task = new ThreadTest();
		Thread thread1 = new Thread(task, "thread1");
		Thread thread2 = new Thread(task, "thread2");
		thread1.start();
		Thread.sleep(1000);
		thread2.start();
	}
}

Implementation of the results

进入线程执行体,当前线程名: thread1
进入同步代码块,当前线程名: thread1
thread1线程进入等待状态,释放同步锁
进入线程执行体,当前线程名: thread2
进入同步代码块,当前线程名: thread2
走出同步代码块,当前线程名: thread2
走出线程执行体,当前线程名: thread2
走出同步代码块,当前线程名: thread1
走出线程执行体,当前线程名: thread1

: Explain the code execution flow
when the main thread creates two sub-thread thread1 and thread2, 2 threads sharing a lock on execution threads in the body, that is, lock objects, the main thread first start thread1 thread, the thread enters the method body If the thread is named thread1 the current thread to wait, that is thread1 wait to release the lock lock when performing the wait method, then other threads can enter the synchronized block, and then went back to the main thread, this time the main thread execution thread .sleep (1000) enter a sleep state, since no other thread executes (Thread1 case in a waiting state), until it is time to sleep behind the main thread execution code at this time after starting thread2 sleep state, the method executable thread thread2 notify the threads of the wake lock lock waiting thread1 objects, then the first thread2 thread of execution threads, the thread wakes thread1 executing the remaining thread of execution code.

Published 236 original articles · won praise 10 · views 10000 +

Guess you like

Origin blog.csdn.net/gunsmoke/article/details/104542330