线程之同步函数

  1. 同步函数使用的锁是this
  2. 同步函数和同步代码块的区别?
    • 同步函数的锁固定是this。
    • 同步代码的锁是任意的对象。
    • 建议使用同步代码块。
  1. 静态同步函数使用的锁是该函数所属的字节码文件对象,可以使用getClass方法获取,也可以使用当前类.class来获取。

  

  设计模式之单例模式

  

package com.google.thread;

/**
 * 饿汉式
 * 
 * @author CAOXIAOYANG
 * 
 */
/*class Single {
	private static final Single s = new Single();

	private Single() {
	}

	public static Single getInstance() {
		return s;
	}
}*/
/**
 * 懒汉式
 * @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) {
	}
}

  单例模式的线程安全性问题。

  死锁问题

  死锁的原因

    两个及两个以上的线程竞争对方的资源

  死锁的代码。

  

 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) {//同步函数的锁是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();//开启线程
40         try {
41             Thread.sleep(1);
42         } catch (InterruptedException e) {
43             e.printStackTrace();
44         }
45         t.flag=false;
46         t2.start();
47     }
48 }

猜你喜欢

转载自www.cnblogs.com/CAOXIAOYANG/p/8988973.html