1. 程式人生 > >java中自定義鎖實現synchronized功能

java中自定義鎖實現synchronized功能

public class Test {
private static long count = 0;
private Lock lock = new Lock();
private int m = 0;
private int a = 0;
private int b = 0;


public static void main(String[] args) {
try {
Test t = new Test();
for (int i = 0; i < 500; i++) {
new Thread(new ThreadTest(t)).start();
}


} catch (Exception ex) {
ex.printStackTrace();
}
}


/**
* 通過互斥鎖來實現 synchronized 的效果

* @param a
* @param b
*/
public void add(int a, int b,int c) throws Exception {
// System.out.println(count++);
lock.lockUp();
try {
this.a = a;
this.b = b;
this.m = this.a + this.b;
if (this.m != c) {
System.out.println(Thread.currentThread().getName()
+ ":error:::" + this.m + ":" + c);
}
} finally {
lock.unlock();
}
}
}


class Lock {
private Integer a = 0;


/**
* 加鎖

* @throws InterruptedException
*/
public synchronized void lockUp() throws InterruptedException {
while (a > 0) {
this.wait();
}
a++;
}


/**
* 解鎖
*/
public synchronized void unlock() {
a--;
notifyAll();
}
}


class ThreadTest implements Runnable {
private Test t;


public ThreadTest(Test t) {
this.t = t;
}


public void run() {
int a = 0;
int b = 0;
while (true) {
try {
if (a == Integer.MAX_VALUE) {
a = 0;
}
if (b == Integer.MAX_VALUE) {
b = 0;
}
a = a + 1;
b = b + 1;
int c = a + b;
this.t.add(a, b,c);

Thread.sleep(2);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}