java 中多线程的同步函数的运用

/*
 * 需求:
 * 银行有一个金库
 * 有两个储户,分别存300元。每次存100 , 存三次
 * 
 * 这个是有线程问题的,
 * 
 * 我们应该通过下边的三个方法来查找问题
 * 1.明确哪些代码是多线程运行的代码
 * 2.明确共享数据
 * 3.明确多线程运行代码中哪些是操作共享数据的
 */

class Bank
{
  private int sum;
   public synchronized void   add (int n)
{
sum = sum + n;
try {Thread.sleep (10);}catch (Exception e){}
System.out.println ("sum="+ sum);
}
}

class Cus implements Runnable
{
    private Bank bank = new Bank ();
    public void run(){
        for (int x=0; x<3;x++){
            bank.add(100);
            
        }
        
    }
}
public class BankDemo {

    public static void main(String[] args) {
        
Cus cus = new Cus ();
Thread t1 = new Thread (cus);
Thread t2 = new Thread (cus);
t1.start();
t2.start();

    }

}

上边代码中的synchorinized 关键字 是可以放到函数前边的,这就叫做同步函数 跟下边的用法是一个作用

Object obj = new Object ();

Synchronized (obj) {

//需要同步的代码块

}

上边的代码的例子中的锁使用的对象其实就是自己本身this,在多线程操作中为了让线程安全,必须使用同一把锁

如果同步函数被static 修饰,那么就不是this了 因为静态方法中没有this 方法

静态进内存是,内存中没有本类对象,但是一定有该类对应的字节码文件对象,叫做类名.class 该对象的类型是Class

静态的同步方法是 使用的锁是该方法坐在类的字节码文件对象。类名.class

l例如

 1 class Ticket implements Runnable
 2 {
 3      private  static int tick = 100;
 4      boolean flag = true;
 5      Object obj = new Object();
 6      public void run (){
 7          
 8          if (flag){
 9          while (true){
10              
11              synchronized(Ticket.class){
12                 if (tick > 0){
13                     try {
14                         Thread.sleep (10);
15                     }
16                     catch (Exception a)
17                     {
18                         
19                         
20                     }
21                     System.out.println(Thread.currentThread().getName()+"sale:"+tick--);
22                 }
23              }
24                 
25             }
26      }else
27          while (true)
28          show();
29      }
30          public static synchronized void show()
31      {
32          
33          if (tick > 0){
34                 try {
35                     Thread.sleep (10);
36                 }
37                 catch (Exception a)
38                 {
39                     
40                     
41                 }
42                 System.out.println(Thread.currentThread().getName()+"sale:"+tick--);
43             }
44      }
45      }
46 
47 
48 
49 public class ThreadDemo {
50 
51     public static void main(String[] args) {
52         // TODO Auto-generated method stub
53 
54         Ticket t = new Ticket ();
55         Thread t1 = new Thread (t);
56         Thread t2 = new Thread (t);
57 //        Thread t3 = new Thread (t);
58 //        Thread t4 = new Thread (t);
59         t1.start();
60         t2.start();
61 //        t3.start();
62 //        t4.start();
63         
64     }
65 
66 }
原文地址:https://www.cnblogs.com/machao/p/4593275.html