...
 
Commits (4)
    https://gitcode.net/k316378085/java-study/-/commit/adf0dd14b71fc14656d4127bb4c4ac76b4cc0caa feat: synchronized 代码实例 2023-10-25T13:35:53+08:00 ex_kongxiang ex_kongxiang@partner.midea.com https://gitcode.net/k316378085/java-study/-/commit/9563c50773017dcf9299e4a9da353f13b205e4a2 feat : 锁中断 2023-10-25T19:34:47+08:00 ex_kongxiang ex_kongxiang@partner.midea.com https://gitcode.net/k316378085/java-study/-/commit/d3e5903d454ad8473fd706c9ac609384b023623e feat : 工具类测试 2023-10-26T11:00:34+08:00 ex_kongxiang ex_kongxiang@partner.midea.com https://gitcode.net/k316378085/java-study/-/commit/4cfec70118a964024c9be72e01efadc26cf4171a feat : 工具类测试 2023-10-26T11:00:47+08:00 ex_kongxiang ex_kongxiang@partner.midea.com
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @author 孔翔
* @since 2023-10-25
* copyright for author : 孔翔 at 2023-10-25
* java-study
*/
public class ReadWriteLockDemo {
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private int value;
public int getValue() {
System.out.println("读:" + value);
return value;
}
public void update(int value) {
int sum = this.value + value;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
this.value = sum;
}
public int read() {
Lock lock = readWriteLock.readLock();
try {
lock.lock();
Thread.sleep(10);
System.out.println("读锁:after");
return getValue();
} catch (InterruptedException e) {
throw new IllegalArgumentException();
} finally {
lock.unlock();
}
}
public void updateSafe(int value) {
Lock lock = readWriteLock.writeLock();
try {
System.out.println("writeLock:before");
lock.lock();
Thread.sleep(1000);
System.out.println("writeLock:after");
update(value);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}
import lombok.Getter;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author 孔翔
* @since 2023-10-25
* copyright for author : 孔翔 at 2023-10-25
* java-study
*/
public class ReentrantLockDemo {
public int getMoney() {
return money;
}
private int money;
/**
* 存钱
*
* @param money
*/
public void save(int money) {
int sum = this.money + money;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
this.money = sum;
}
// 获取ReentrantLock对象
ReentrantLock lock = new ReentrantLock();
public void saveSafe(int money) {
// 加锁 获取不到锁一直等待直到获取锁
lock.lock();
try {
// 临界区
save(money);
// 需要执行的代码
} finally {
// 释放锁 如果不释放其他线程就获取不到锁
lock.unlock();
}
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
/**
* @author 孔翔
* @since 2023-10-25
* copyright for author : 孔翔 at 2023-10-25
* java-study
*/
public class SimpleThreadUtils {
/**
* 创建循环测试线程
*
* @param threadCount 线程数量
* @param threadName 线程名
* @param loopCount 循环次数
* @param consumer 执行代码 参数
*/
public static List<Thread> newLoopThread(int threadCount, String threadName, long loopCount, Consumer<AThread> consumer) {
List<Thread> list = new ArrayList<>();
for (int i = 0; i < threadCount; i++) {
final int threadNo = i;
AThread thread = new AThread(() -> {
System.out.println("当前线程-"+ Thread.currentThread().getName()+": 开始");
int j = 0;
while (j++ < loopCount) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
consumer.accept((AThread)Thread.currentThread());
}
System.out.println("当前线程-"+ Thread.currentThread().getName()+": 结束");
}, threadName + ":" + i);
thread.setNo(i);
thread.start();
list.add(thread);
}
return list;
}
public static void wait(long gap , Runnable runnable) {
while (true) {
try {
Thread.sleep(gap);
runnable.run();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
......@@ -11,7 +11,7 @@ public class SynchronizedLock {
private int value;
public void update(int value) {
public void update(int value) {
int sum = this.value + value;
try {
Thread.sleep(10);
......@@ -21,8 +21,11 @@ public class SynchronizedLock {
this.value = sum;
}
public synchronized void updateSafe(int value) {
/**
* synchronized 方法
* @param value
*/
public synchronized void updateSafe(int value) {
int sum = this.value + value;
try {
Thread.sleep(10);
......@@ -32,6 +35,34 @@ public class SynchronizedLock {
this.value = sum;
}
/**
* synchronized 块
* @param value
*/
public void updateSafeBlock(int value) {
synchronized (this) {
int sum = this.value + value;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
this.value = sum;
}
}
public void updateSafeBlockClass(int value) {
synchronized (SynchronizedLock.class) {
int sum = this.value + value;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
this.value = sum;
}
}
public int getValue() {
return value;
}
......
import org.testng.annotations.Test;
import java.util.concurrent.CountDownLatch;
/**
* @author 孔翔
* @since 2023-10-25
* copyright for author : 孔翔 at 2023-10-25
* java-study
*/
public class CountDownLatchTest {
@Test
public void test() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
SimpleThreadUtils.newLoopThread(5, "cd", 1, (t) -> {
int i = t.getNo() * 1000;
try {
Thread.sleep(i);
} catch (InterruptedException e) {
}
System.out.println("加载资源线程:"+t.getName()+": 花费了 " + i + "s");
countDownLatch.countDown();
});
countDownLatch.await();
System.out.println("开始游戏");
}
}
import org.testng.annotations.Test;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
/**
* @author 孔翔
* @since 2023-10-25
* copyright for author : 孔翔 at 2023-10-25
* java-study
*/
public class CyclicBarrierTest {
@Test
public void test() throws InterruptedException {
CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
SimpleThreadUtils.newLoopThread(5, "cd", 1, (t) -> {
while (true) {
int i = t.getNo() * 1000;
try {
Thread.sleep(i);
} catch (InterruptedException e) {
}
System.out.println(":" + t.getName() + ": 准备好了");
try {
cyclicBarrier.await();
System.out.println(" 冲。。。 :" + t.getName());
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
}
});
SimpleThreadUtils.wait(10000,()->{});
}
}
import org.testng.annotations.Test;
import java.util.concurrent.Exchanger;
/**
* @author 孔翔
* @since 2023-10-25
* copyright for author : 孔翔 at 2023-10-25
* java-study
*/
public class ExchangerTest {
@Test
public void test() {
Exchanger<String> exchanger = new Exchanger<>();
SimpleThreadUtils.newLoopThread(2,"ex",2,(t)->{
if (t.getNo() == 0){
try {
String exchange = exchanger.exchange("我先到了,你死定了");
System.out.println(t.getName()+":"+exchange);
} catch (InterruptedException e) {
}
}else {
try {
Thread.sleep(5000);
String exchange = exchanger.exchange("先到了吧,去死吧");
System.out.println(t.getName()+":"+exchange);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
SimpleThreadUtils.wait(1000,()->{});
}
}
import org.testng.annotations.Test;
/**
* @author 孔翔
* @since 2023-10-25
* copyright for author : 孔翔 at 2023-10-25
* java-study
*/
public class ReadWriteLockDemoTest {
ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();
@Test
public void testGetValue() {
SimpleThreadUtils.newLoopThread(10,"readWrite",10000,(t)->{
if (t.getNo() < 3){
readWriteLockDemo.updateSafe(100);
}else {
int read = readWriteLockDemo.read();
// System.out.println(t.getName()+":::: read : " +read );
}
});
SimpleThreadUtils.wait(1000,()->{});
}
}
//Generated with love by TestMe :) Please report issues and submit feature requests at: http://weirddev.com/forum#!/testme
\ No newline at end of file
import org.testng.annotations.Test;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author 孔翔
* @since 2023-10-25
* copyright for author : 孔翔 at 2023-10-25
* java-study
*/
public class ReentrantLockTest {
ReentrantLockDemo reentrantLockDemo = new ReentrantLockDemo();
@Test
public void testUpdate() {
SimpleThreadUtils.newLoopThread(2, "kx-th", 10, (threadNo) -> {
if (threadNo.getName().contains("0")) {
reentrantLockDemo.save(100);
} else {
reentrantLockDemo.save(-80);
}
System.out.println("实时:" + threadNo.getName() + ":::" + reentrantLockDemo.getMoney());
});
SimpleThreadUtils.wait(1000, () -> {
System.out.println("监控:" + reentrantLockDemo.getMoney());
});
}
@Test
public void testUpdateSafe() {
SimpleThreadUtils.newLoopThread(2, "kx-th", 10, (threadNo) -> {
if (threadNo.getName().contains("0")) {
reentrantLockDemo.saveSafe(100);
} else {
reentrantLockDemo.saveSafe(-80);
}
System.out.println("实时:" + threadNo.getName() + ":::" + reentrantLockDemo.getMoney());
});
SimpleThreadUtils.wait(1000, () -> {
System.out.println("监控:" + reentrantLockDemo.getMoney());
});
}
@Test
public void testLockInterupted() {
ReentrantLock lock = new ReentrantLock();
// 主线程获取锁
lock.lock();
AtomicReference<Thread> t1 = new AtomicReference<>();
SimpleThreadUtils.newLoopThread(2, "Kx", 1000, (t) -> {
if (t.getName().contains("0")) {
if (t1.get() == null) {
t1.set(t);
}
try {
System.out.println("获取锁 线程:" + t.getName() + ":::");
// 获取锁: 阻塞
lock.lockInterruptibly();
System.out.println("获取锁成功 线程:" + t.getName() + ":::");
} catch (InterruptedException e) {
System.out.println(" 被打断 线程:" + t.getName() + ":::");
}
} else {
if (t1.get() != null) {
t1.get().interrupt();
System.out.println("中断 线程:" + t.getName() + ":::");
} else {
System.out.println("中断 线程 没有准备:" + t.getName() + ":::");
}
}
});
SimpleThreadUtils.wait(10000, () -> {
});
}
@Test
public void testLockTryLock() {
ReentrantLock lock = new ReentrantLock();
SimpleThreadUtils.newLoopThread(3, "t", 1000, (t) -> {
boolean b = lock.tryLock();
try {
try {
if (b) {
System.out.println(t.getName() + "获取到锁,处理一分钟");
Thread.sleep(1000);
} else {
System.out.println(t.getName() + "获取到锁失败");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
}
} finally {
if (b) {
lock.unlock();
}
}
});
SimpleThreadUtils.wait(10000, () -> {
});
}
@Test
public void testCondition() {
ReentrantLock lock = new ReentrantLock();
// 等待 A(条件变量)
Condition ac = lock.newCondition();
// 等外 B(条件变量)
Condition bc = lock.newCondition();
SimpleThreadUtils.newLoopThread(2, "t", 1000, (t) -> {
try {
print("Lock..................");
lock.lock();
if (t.getNo() == 0){
print("等待...");
ac.await();
print("等待结束..");
}else if(t.getNo() == 1){
print("通知取消等待...");
ac.signal();
print("通知取消等待执行...");
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
});
SimpleThreadUtils.wait(10000, () -> {
});
}
public void print(String msg){
System.out.println(String.format("%s:::%s",Thread.currentThread().getName(),msg));
}
}
//Generated with love by TestMe :) Please report issues and submit feature requests at: http://weirddev.com/forum#!/testme
\ No newline at end of file
import org.testng.annotations.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
/**
* @author 孔翔
* @since 2023-10-25
* copyright for author : 孔翔 at 2023-10-25
* java-study
*/
public class SemaphoreTest {
@Test
public void test() throws InterruptedException {
Semaphore semaphore = new Semaphore(5);
SimpleThreadUtils.newLoopThread(10, "cd", 10, (t) -> {
try {
semaphore.acquire();
int i = t.getNo() * 1000;
try {
Thread.sleep(i);
} catch (InterruptedException e) {
}
System.out.println("加载资源线程:"+t.getName()+": 花费了 " + i + "s");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}finally {
semaphore.release();
}
});
SimpleThreadUtils.wait(10000,()->{});
}
}
......@@ -19,7 +19,7 @@ public class SynchronizedLockTest {
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronizedLock.updateSafe(100);
synchronizedLock.updateSafeBlockClass(100);
System.out.println(Thread.currentThread().getName()+":"+synchronizedLock.getValue());
}
}).start();
......@@ -31,7 +31,7 @@ public class SynchronizedLockTest {
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronizedLock.updateSafe(-80);
synchronizedLock.updateSafeBlockClass(-80);
System.out.println(Thread.currentThread().getName()+":"+synchronizedLock.getValue());
}
}).start();
......
......@@ -6,8 +6,23 @@
*/
public class AThread extends Thread {
@Override
public void run() {
System.out.println("hello : 我是A Thread");
public AThread() {
}
public AThread(Runnable task, String name) {
super(task, name);
}
private int no;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
}