69 lines
2.1 KiB
Java
69 lines
2.1 KiB
Java
package bunny.thread;
|
|
|
|
import java.util.concurrent.locks.ReentrantLock;
|
|
|
|
public class ThreadTest3 {
|
|
private static int count = 0;
|
|
private static Integer threadCount = 0;
|
|
private static Integer lockCount = 0;
|
|
private static Integer lockReentrantLockCount = 0;
|
|
private static final Object lockObject = new Object();
|
|
private static final ReentrantLock lock = new ReentrantLock();
|
|
|
|
/**
|
|
* * 资源竞争代码示例
|
|
*/
|
|
public static void main(String[] args) {
|
|
// 这是单线程下没有竞争的示例
|
|
for (int i = 0; i < 10; i++) {
|
|
for (int j = 0; j < 1000; j++) {
|
|
count++;
|
|
}
|
|
}
|
|
|
|
// 有资源竞争,值不确定是多少,每一次运行都不一样
|
|
for (int i = 0; i < 10; i++) {
|
|
new Thread(() -> {
|
|
for (int j = 0; j < 1000; j++) {
|
|
threadCount++;
|
|
}
|
|
}).start();
|
|
}
|
|
|
|
// 使用对象锁解决这个问题
|
|
for (int i = 0; i < 10; i++) {
|
|
new Thread(() -> {
|
|
synchronized (lockObject) {
|
|
for (int j = 0; j < 1000; j++) {
|
|
lockCount++;
|
|
}
|
|
}
|
|
}).start();
|
|
}
|
|
|
|
// 使用锁解决
|
|
for (int i = 0; i < 10; i++) {
|
|
new Thread(() -> {
|
|
lock.lock();
|
|
try {
|
|
for (int j = 0; j < 1000; j++) {
|
|
lockReentrantLockCount++;
|
|
}
|
|
} finally {
|
|
lock.unlock();
|
|
}
|
|
}).start();
|
|
}
|
|
|
|
try {
|
|
Thread.sleep(1000);
|
|
} catch (InterruptedException e) {
|
|
System.out.println(e.getMessage());
|
|
}
|
|
System.out.println("count 值:" + count);
|
|
System.out.println("threadCount 值:" + threadCount);
|
|
System.out.println("lockCount 值:" + lockCount);
|
|
System.out.println("lockReentrantLockCount 值:" + lockReentrantLockCount);
|
|
}
|
|
}
|