Reentrant lock and wait (), notify ()

1. Java objects premise call wait (), and notify () method is:

             The current thread must obtain a lock (Monitor) of the object, otherwise it will throw IllegalMonitorStateException, and the two methods must be called synchronous code block. wait (): thread to block access to the current object.

 

2. reentrant lock: also known as recursive lock, i.e. after obtaining the same outer thread lock function, when the function into the interior, inside the lock function can be obtained, meaning that the resulting reentrant prevent deadlocks. Java, synchronized and ReentrantLock are reentrant lock. The following code execution results: Each thread name will be printed twice in a row.

 1 public class SynchronizedLock {
 2     public static void main(String[] args) {
 3      Test1 t1=new Test1();
 4      new Thread(t1,"1_Thread").start();
 5      new Thread(t1,"2_Thread").start();
 6      new Thread(t1,"3_Thread").start();
 7 
 8     }
 9 }
10 class Test1 implements Runnable{
11     @Override
12     public void run() {
13         Method1();
14 
15     }
16     public synchronized void Method1(){
17         System.out.println(Thread.currentThread().getName());
18         Method2();
19     }
20 
21     private synchronized void Method2() {
22         System.out.println(Thread.currentThread().getName());
23 
24     }
25 }

 

Guess you like

Origin www.cnblogs.com/xbfchder/p/10972573.html