- The lock used by the synchronized function is this
- Difference between synchronized function and synchronized code block?
- The lock of a synchronized function is fixed at this.
- Locks for synchronized code are arbitrary objects.
- Synchronized code blocks are recommended.
- The lock used by the static synchronization function is the bytecode file object to which the function belongs, which can be obtained by using the getClass method, or by using the current class .class.
singleton design pattern
package com.google.thread; /** * Hungry Chinese * * @author CAOXIAOYANG * */ /*class Single { private static final Single s = new Single(); private Single() { } public static Single getInstance() { return s; } }*/ /** * Lazy * @author CAOXIAOYANG * */ /*class Single { private static Single s = null; private Single() { } public static Single getInstance() { if(s==null){ s = new Single(); } return null; } }*/ public class ThreadDemo extends Thread { public static void main(String[] args) { } }
The thread safety issue of the singleton pattern.
deadlock problem
Cause of deadlock
Two or more threads compete for each other's resources
deadlocked code.
1 package com.google.thread; 2 /** 3 * 死锁的示例。 4 * @author CAOXIAOYANG 5 * 6 */ 7 class Ticker implements Runnable{ 8 public static int num = 100; 9 Object obj=new Object(); 10 boolean flag = true; 11 public void run() { 12 if (flag) { 13 while (true) { 14 synchronized (obj) { // The lock of the synchronized function is this 15 fun(); 16 } 17 } 18 } else { 19 while ( true ) { 20 fun(); 21 } 22 } 23 24 } 25 private synchronized void fun() { 26 synchronized (obj) { 27 if (num > 0 ) { 28 System.out.println(Thread.currentThread().getName() + "......." + num--); 29 } 30 } 31 } 32 } 33 public class ThreadDemo extends Thread { 34 public static void main(String[] args) { 35 Ticker t = new Ticker(); 36 Thread t1=new Thread(t);//创建线程 37 Thread t2=new Thread(t); 38 39 t1.start();//Start thread 40 try { 41 Thread.sleep(1 ); 42 } catch (InterruptedException e) { 43 e.printStackTrace(); 44 } 45 t.flag= false ; 46 t2.start(); 47 } 48 }