Java多线程系列--“基础篇”04之 synchronized关键字(三)

2014-11-24 03:24:23 · 作者: · 浏览: 9
onized同步块的方法
17 public void nonSynMethod() {
18 synchronized(this) {
19 try {
20 for (int i = 0; i < 5; i++) {
21 Thread.sleep(100);
22 System.out.println(Thread.currentThread().getName() + " nonSynMethod loop " + i);
23 }
24 } catch (InterruptedException ie) {
25 }
26 }
27 }
28 }
29
30 public class Demo3 {
31
32 public static void main(String[] args) {
33 final Count count = new Count();
34 // 新建t1, t1会调用“count对象”的synMethod()方法
35 Thread t1 = new Thread(
36 new Runnable() {
37 @Override
38 public void run() {
39 count.synMethod();
40 }
41 }, "t1");
42
43 // 新建t2, t2会调用“count对象”的nonSynMethod()方法
44 Thread t2 = new Thread(
45 new Runnable() {
46 @Override
47 public void run() {
48 count.nonSynMethod();
49 }
50 }, "t2");
51
52
53 t1.start(); // 启动t1
54 t2.start(); // 启动t2
55 }
56 }
复制代码
运行结果:
复制代码
t1 synMethod loop 0
t1 synMethod loop 1
t1 synMethod loop 2
t1 synMethod loop 3
t1 synMethod loop 4
t2 nonSynMethod loop 0
t2 nonSynMethod loop 1
t2 nonSynMethod loop 2
t2 nonSynMethod loop 3
t2 nonSynMethod loop 4
复制代码
结果说明:
主线程中新建了两个子线程t1和t2。t1和t2运行时都调用synchronized(this),这个this是Count对象(count),而t1和t2共用count。因此,在t1运行时,t2会被阻塞,等待t1运行释放“count对象的同步锁”,t2才能运行。
3. synchronized方法 和 synchronized代码块
“synchronized方法”是用synchronized修饰方法,而 “synchronized代码块”则是用synchronized修饰代码块。
synchronized方法示例
public synchronized void foo1() {
System.out.println("synchronized methoed");
}
synchronized代码块
public void foo2() {
synchronized (this) {
System.out.println("synchronized methoed");
}
}
synchronized代码块中的this是指当前对象。也可以将this替换成其他对象,例如将this替换成obj,则foo2()在执行synchronized(obj)时就获取的是obj的同步锁。
synchronized代码块可以更精确的控制冲突限制访问区域,有时候表现更高效率。下面通过一个示例来演示:
复制代码
1 // Demo4.java的源码
2 public class Demo4 {
3
4 public synchronized void synMethod() {
5 for(int i=0; i<1000000; i++)
6 ;
7 }
8
9 public void synBlock() {
10 synchronized( this ) {
11 for(int i=0; i<1000000; i++)
12 ;
13 }
14 }
15
16 public static void main(String[] args) {
17 Demo4 demo = new Demo4();
18
19 long start, diff;
20 start = System.currentTimeMillis(); // 获取当前时间(millis)
21 demo.synMethod(); // 调用“synchronized方法”
22 diff = System.currentTimeMillis() - start; // 获取“时间差值”
23 System.out.println("synMethod() : "+ diff);
24
25 start = System.currentTimeMillis(); // 获取当前时间(millis)
26 demo.synBlock(); // 调用“synchronized方法块”
27 diff = System.currentTimeMillis() - start; // 获取“时间差值”
28 System.out.println("synBlock() : "+ diff);
29 }
30 }
复制代码
(某一次)执行结果:
synMethod() : 11
synBlock() : 3
4. 实例锁 和 全局锁
实例锁 -- 锁在某一个实例对象上。如果该类是单例,那么该锁也具有全局锁的概念。
实例锁对应的就是synchronized关键字。
全局锁 -- 该锁针对的是类,无论实例多少个对象,那么线程都共享该锁。
全局锁对应的就是static synchronized(或者是锁在该类的class或者cla