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();
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值