847. java中加锁的⽅式有哪些,如何实现怎么个写法.

  1. java中有两种锁:⼀种是⽅法锁或者对象锁(在⾮静态⽅法或者代码块上加锁),第⼆种是类锁(在静态⽅法或者class上加锁);
  2. 注意:其他线程可以访问未加锁的⽅法和代码;synchronized同时修饰静态⽅法和实例⽅法,但是运⾏结果是交替进⾏的,这证明了类锁和对象锁是两个不⼀样的锁,控制着不同的区域,它们是互不⼲扰的。
  3. 示例代码:
    1. ⽅法锁和同步代码块:
1 public class TestSynchronized 
2 { 
3 public void test1() 
4 { 
5 synchronized(this) 
6 { 
7 int i = 5; 
8 while( i-- > 0) 
9 { 
10 System.out.println(Thread.currentThread().getName() + " : " + i); 
11 try 
12 { 
13 Thread.sleep(500); 
14 } 
15 catch (InterruptedException ie) 
16 { 
17 } 
18 } 
19 } 
20 } 
21 
22 public synchronized void test2() 
23 { 
24 int i = 5; 
25 while( i-- > 0) 
26 { 
27 System.out.println(Thread.currentThread().getName() + " : " + i); 
28 try 
29 { 
30 Thread.sleep(500); 
31 } 
32 catch (InterruptedException ie) 
33 { 
34 } 
35 } 
36 } 
37 
38 public static void main(String[] args) 
39 { 
40 final TestSynchronized myt2 = new TestSynchronized(); 
41 Thread test1 = new Thread( new Runnable() { public void run() { myt2.test1(); } },
42 Thread test2 = new Thread( new Runnable() { public void run() { myt2.test2(); } },
43 test1.start();; 
44 test2.start(); 
45 // TestRunnable tr=new TestRunnable(); 
46 // Thread test3=new Thread(tr); 
47 // test3.start(); 
48 } 
49 }
2. 类锁:
1 public class TestSynchronized 
2 { 
3 public void test1() 
4 { 
5 synchronized(TestSynchronized.class) 
6 { 
7 int i = 5; 
8 while( i-- > 0) 
9 { 
10 System.out.println(Thread.currentThread().getName() + " : " + i); 
11 try 
12 { 
13 Thread.sleep(500); 
14 } 
15 catch (InterruptedException ie) 
16 { 
17 } 
18 } 
19 } 
20 } 
21 
22 public static synchronized void test2() 
23 { 
24 int i = 5; 
25 while( i-- > 0) 
26 { 
27 System.out.println(Thread.currentThread().getName() + " : " + i); 
28 try 
29 { 
30 Thread.sleep(500); 
31 } 
32 catch (InterruptedException ie) 
33 { 
34 } 
35 } 
36 } 
37 
38 public static void main(String[] args) 
39 { 
40 final TestSynchronized myt2 = new TestSynchronized(); 
41 Thread test1 = new Thread( new Runnable() { public void run() { myt2.test1(); } },
42 Thread test2 = new Thread( new Runnable() { public void run() { TestSynchronized.test2
43 test1.start(); 
44 test2.start(); 
45 // TestRunnable tr=new TestRunnable(); 
46 // Thread test3=new Thread(tr); 
47 // test3.start(); 
48 } 
49 
50 }