Discuss / Java / 自己动手,丰衣足食

自己动手,丰衣足食

Topic source

🌙

#1 Created at ... [Delete] [Delete and Lock User]

public class MyReentrantLock {

public static void main(String[] args) {
Thread t = new Thread(() -> {
Counter counter = new Counter();
int add = counter.add(88);
System.out.println(add);
});
// 启动新线程
t.start();

Counter counter = new Counter();

Thread t2 = new Thread(() -> {
int add = 0;
try {
add = counter.add1(66);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(add);
});
// 启动新线程
t2.start();

Thread t3 = new Thread(() -> {
int add = 0;
try {
add = counter.add1(99);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(add);
});
// 启动新线程
t3.start();

}

}

class Counter {
private final Lock lock = new ReentrantLock();
private int count;

public int add(int n) {
lock.lock();
try {
count += n;
} finally {
lock.unlock();
}
return count;
}

/**
* 设置等待时间
*
* @param n
* @return
*/
public int add1(int n) throws InterruptedException {

if (lock.tryLock(1, TimeUnit.SECONDS)) {
try {
count += n;
} finally {
Thread.sleep(2000);
lock.unlock();
}
} else {
return 100;
}

return count;
}

}


  • 1

Reply