本文实例讲述了Java互斥锁。分享给大家供大家参考。具体分析如下:
互斥锁,常常用于多个线程访问独占式资源,比如多个线程同时写一个文件,虽然互斥访问方式不够高效,但是对于一些应用场景却很有意义
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
//没有互斥锁的情况(可以自己跑跑看运行结果):
public class LockDemo {
// private static Object lock = new Object();
// static确保只有一把锁
private int i = 0 ;
public void increaseI() {
// synchronized (lock) {
for ( int k= 0 ;k< 10 ;k++) { // 对i执行10次增1操作
i++;
}
System.out.println(Thread.currentThread().getName() + "线程,i现在的值:" + i);
// }
}
public static void main(String[] args) {
LockDemo ld = new LockDemo();
int threadNum = 1000 ;
// 选择1000个线程让结果更加容易观测到
MyThread[] threads = new MyThread[threadNum];
for ( int i= 0 ;i<threads.length;i++) {
threads[i] = new MyThread(ld);
// 所有线程共用一个LockDemo对象
threads[i].start();
}
}
}
class MyThread extends Thread {
LockDemo ld;
public MyThread(LockDemo ld) {
this .ld = ld;
}
public void run() {
ld.increaseI();
}
}
//加上互斥锁以后:
public class LockDemo {
private static Object lock = new Object();
// static确保只有一把锁
private int i = 0 ;
public void increaseI() {
synchronized (lock) {
for ( int k= 0 ;k< 10 ;k++) {
// 对i执行10次增1操作
i++;
}
System.out.println(Thread.currentThread().getName() + "线程,i现在的值:" + i);
}
}
public static void main(String[] args) {
LockDemo ld = new LockDemo();
int threadNum = 1000 ;
// 选择1000个线程让结果更加容易观测到
MyThread[] threads = new MyThread[threadNum];
for ( int i= 0 ;i<threads.length;i++) {
threads[i] = new MyThread(ld);
// 所有线程共用一个LockDemo对象
threads[i].start();
}
}
}
class MyThread extends Thread {
LockDemo ld;
public MyThread(LockDemo ld) {
this .ld = ld;
}
public void run() {
ld.increaseI();
}
}
|
希望本文所述对大家的java程序设计有所帮助。