Initial commit

This commit is contained in:
2025-11-06 10:32:28 +08:00
commit 1f42e79061
112 changed files with 5101 additions and 0 deletions

29
Classwork/.gitignore vendored Normal file
View File

@@ -0,0 +1,29 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

8
Classwork/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

5
Classwork/.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,5 @@
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
Classwork/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Classwork.iml" filepath="$PROJECT_DIR$/Classwork.iml" />
</modules>
</component>
</project>

4
Classwork/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings" defaultProject="true" />
</project>

11
Classwork/Classwork.iml Normal file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,40 @@
package Bank;
public class Bank {
private int money;
private String name;
public Bank(String name, int money) {
this.name = name;
this.money = money;
}
public synchronized void deposit(int m) {
money += m;
}
public synchronized boolean withdraw(int m) {
if (money >= m) {
money -= m;
check();
return true;
} else {
return false;
}
}
public String getName() {
return name;
}
private void check() {
if (money < 0) {
System.out.println("可用余额为负数money=" + money);
}
/*
else {
System.out.println("money=" + money);
}
*/
}
}

View File

@@ -0,0 +1,17 @@
package Bank;
public class ClientThread extends Thread{
private Bank bank;
public ClientThread(Bank bank) {
this.bank = bank;
}
@Override
public void run(){
while (true){
boolean ok=bank.withdraw(1000);
if(ok){
bank.deposit(1000);
}
}
}
}

View File

@@ -0,0 +1,15 @@
package Bank;
public class MainTest {
public static void main(String[] args) {
Bank bank = new Bank("a bad bank", 1000);
new ClientThread(bank).start();
new ClientThread(bank).start();
new ClientThread(bank).start();
new ClientThread(bank).start();
new ClientThread(bank).start();
new ClientThread(bank).start();
new ClientThread(bank).start();
new ClientThread(bank).start();
}
}

View File

@@ -0,0 +1,45 @@
package Buffer;
import java.nio.ByteBuffer;
import static Buffer.BufferOperation.bufferToString;
public class BufferCreateIO {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10);
System.out.println("初始状态: " + bufferToString(buffer));
// 向缓冲区依次写入字节 1, 2, 3, 4, 5
buffer.put((byte) 1);
buffer.put((byte) 2);
buffer.put((byte) 3);
buffer.put((byte) 4);
buffer.put((byte) 5);
System.out.println("写入5个字节后: " + bufferToString(buffer));
// 切换为读模式
buffer.flip();
System.out.println("调用flip()后 (读模式): " + bufferToString(buffer));
// 读取并打印所有数据
System.out.print("读取数据: ");
while (buffer.hasRemaining()) {
System.out.print(buffer.get() + " ");
}
System.out.println("\n读取完毕后: " + bufferToString(buffer));
// 清空缓冲区
buffer.clear();
System.out.println("调用clear()后: " + bufferToString(buffer));
// 验证是否可重新写入
buffer.put((byte) 6);
System.out.println("重新写入一个字节 (6) 后: " + bufferToString(buffer));
buffer.flip();
System.out.print("读取新写入的数据: ");
while (buffer.hasRemaining()) {
System.out.print(buffer.get() + " ");
}
System.out.println();
}
}

View File

@@ -0,0 +1,24 @@
package Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.IntBuffer;
public class BufferOperation {
public static String bufferToString(ByteBuffer buffer) {
return "pos=" + buffer.position() + " lim=" + buffer.limit() + " cap=" + buffer.capacity();
}
public static String charBufferToString(CharBuffer buffer) {
return "pos=" + buffer.position() + " lim=" + buffer.limit() + " cap=" + buffer.capacity();
}
public static String intBufferToString(IntBuffer buffer) {
return "pos=" + buffer.position() + " lim=" + buffer.limit() + " cap=" + buffer.capacity();
}
public static String bytesToHex(byte[] bytes, int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(String.format("%02X ", bytes[i]));
}
return sb.toString().trim();
}
}

View File

@@ -0,0 +1,56 @@
package Data;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Data {
private final char[] buffer;
private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Lock readLock = rwLock.readLock();
private final Lock writeLock = rwLock.writeLock();
public Data(int size) {
this.buffer = new char[size];
for (int i = 0; i < buffer.length; i++) {
buffer[i] = '*';
}
}
public char[] read() throws InterruptedException {
readLock.lock();
try {
return doRead();
} finally {
readLock.unlock();
}
}
public void write(char c) throws InterruptedException {
writeLock.lock();
try {
doWrite(c);
} finally {
writeLock.unlock();
}
}
private char[] doRead() throws InterruptedException {
char[] newbuf = new char[buffer.length];
for (int i = 0; i < buffer.length; i++) {
newbuf[i] = buffer[i];
}
slowly();
return newbuf;
}
private void doWrite(char c) throws InterruptedException {
for (int i = 0; i < buffer.length; i++) {
buffer[i] = c;
slowly();
}
}
private void slowly() throws InterruptedException {
Thread.sleep(50);
}
}

View File

@@ -0,0 +1,40 @@
package Data;
public class Main {
public static void main(String[] args) {
Data data = new Data(10);
ReaderThread reader1 = new ReaderThread("Reader-1", data);
ReaderThread reader2 = new ReaderThread("Reader-2", data);
ReaderThread reader3 = new ReaderThread("Reader-3", data);
ReaderThread reader4 = new ReaderThread("Reader-4", data);
WriterThread writer1 = new WriterThread("Writer-A", data, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
WriterThread writer2 = new WriterThread("Writer-B", data, "abcdefghijklmnopqrstuvwxyz");
System.out.println("Starting threads...");
reader1.start();
reader2.start();
writer1.start();
reader3.start();
reader4.start();
writer2.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("\nInterrupting threads...");
reader1.interrupt();
reader2.interrupt();
reader3.interrupt();
reader4.interrupt();
writer1.interrupt();
writer2.interrupt();
System.out.println("Main thread finished.");
}
}

View File

@@ -0,0 +1,24 @@
package Data;
public class ReaderThread extends Thread {
private final Data data;
public ReaderThread(String name, Data data) {
super(name);
this.data = data;
}
@Override
public void run() {
try {
while (true) {
char[] readBuf = data.read();
System.out.println(Thread.currentThread().getName() + " reads " + String.valueOf(readBuf));
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " was interrupted.");
Thread.currentThread().interrupt();
}
}
}

View File

@@ -0,0 +1,37 @@
package Data;
public class WriterThread extends Thread {
private final Data data;
private final String filler;
private int index = 0;
public WriterThread(String name, Data data, String filler) {
super(name);
this.data = data;
this.filler = filler;
}
@Override
public void run() {
try {
while (true) {
char c = nextChar();
data.write(c);
System.out.println(Thread.currentThread().getName() + " writes " + c);
Thread.sleep(300);
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " was interrupted.");
Thread.currentThread().interrupt();
}
}
private char nextChar() {
char c = filler.charAt(index);
index++;
if (index >= filler.length()) {
index = 0;
}
return c;
}
}

View File

@@ -0,0 +1,63 @@
package DataLimited;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Data {
private final char[] buffer;
private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Lock readLock = rwLock.readLock();
private final Lock writeLock = rwLock.writeLock();
private final Semaphore readSemaphore = new Semaphore(3);
public Data(int size) {
this.buffer = new char[size];
for (int i = 0; i < buffer.length; i++) {
buffer[i] = '*';
}
}
public char[] read() throws InterruptedException {
readSemaphore.acquire();
try {
readLock.lock();
try {
return doRead();
} finally {
readLock.unlock();
}
} finally {
readSemaphore.release();
}
}
public void write(char c) throws InterruptedException {
writeLock.lock();
try {
doWrite(c);
} finally {
writeLock.unlock();
}
}
private char[] doRead() throws InterruptedException {
char[] newbuf = new char[buffer.length];
for (int i = 0; i < buffer.length; i++) {
newbuf[i] = buffer[i];
}
slowly();
return newbuf;
}
private void doWrite(char c) throws InterruptedException {
for (int i = 0; i < buffer.length; i++) {
buffer[i] = c;
slowly();
}
}
private void slowly() throws InterruptedException {
Thread.sleep(50);
}
}

View File

@@ -0,0 +1,40 @@
package DataLimited;
public class Main {
public static void main(String[] args) {
Data data = new Data(10);
ReaderThread reader1 = new ReaderThread("Reader-1", data);
ReaderThread reader2 = new ReaderThread("Reader-2", data);
ReaderThread reader3 = new ReaderThread("Reader-3", data);
ReaderThread reader4 = new ReaderThread("Reader-4", data);
WriterThread writer1 = new WriterThread("Writer-A", data, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
WriterThread writer2 = new WriterThread("Writer-B", data, "abcdefghijklmnopqrstuvwxyz");
System.out.println("Starting threads...");
reader1.start();
reader2.start();
writer1.start();
reader3.start();
reader4.start();
writer2.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("\nInterrupting threads...");
reader1.interrupt();
reader2.interrupt();
reader3.interrupt();
reader4.interrupt();
writer1.interrupt();
writer2.interrupt();
System.out.println("Main thread finished.");
}
}

View File

@@ -0,0 +1,24 @@
package DataLimited;
public class ReaderThread extends Thread {
private final Data data;
public ReaderThread(String name, Data data) {
super(name);
this.data = data;
}
@Override
public void run() {
try {
while (true) {
char[] readBuf = data.read();
System.out.println(Thread.currentThread().getName() + " reads " + String.valueOf(readBuf));
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " was interrupted.");
Thread.currentThread().interrupt();
}
}
}

View File

@@ -0,0 +1,37 @@
package DataLimited;
public class WriterThread extends Thread {
private final Data data;
private final String filler;
private int index = 0;
public WriterThread(String name, Data data, String filler) {
super(name);
this.data = data;
this.filler = filler;
}
@Override
public void run() {
try {
while (true) {
char c = nextChar();
data.write(c);
System.out.println(Thread.currentThread().getName() + " writes " + c);
Thread.sleep(300);
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " was interrupted.");
Thread.currentThread().interrupt();
}
}
private char nextChar() {
char c = filler.charAt(index);
index++;
if (index >= filler.length()) {
index = 0;
}
return c;
}
}

View File

@@ -0,0 +1,19 @@
package ProducerConsumer.extthread;
import ProducerConsumer.service.RepastService;
public class ThreadC extends Thread {
private RepastService service;
public ThreadC(RepastService service) {
super();
this.service = service;
}
@Override
public void run() {
service.get();
}
}

View File

@@ -0,0 +1,19 @@
package ProducerConsumer.extthread;
import ProducerConsumer.service.RepastService;
public class ThreadP extends Thread {
private RepastService service;
public ThreadP(RepastService service) {
super();
this.service = service;
}
@Override
public void run() {
service.set();
}
}

View File

@@ -0,0 +1,94 @@
package ProducerConsumer.service;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class RepastService {
volatile private Semaphore setSemaphore = new Semaphore(10);// 厨师
volatile private Semaphore getSemaphore = new Semaphore(20);// 就餐者
volatile private ReentrantLock lock = new ReentrantLock();
volatile private Condition setCondition = lock.newCondition();
volatile private Condition getCondition = lock.newCondition();
volatile private Object[] producePosition = new Object[4];
private boolean isEmpty() {
boolean isEmpty = true;
for (int i = 0; i < producePosition.length; i++) {
if (producePosition[i] != null) {
isEmpty = false;
break;
}
}
if (isEmpty == true) {
return true;
} else {
return false;
}
}
private boolean isFull() {
boolean isFull = true;
for (int i = 0; i < producePosition.length; i++) {
if (producePosition[i] == null) {
isFull = false;
break;
}
}
return isFull;
}
public void set() {
try {
// System.out.println("set");
setSemaphore.acquire();// 允许同时最多有10个厨师进行生产
lock.lock();
while (isFull()) {
System.out.println("生产者在等待");
setCondition.await();
}
for (int i = 0; i < producePosition.length; i++) {
if (producePosition[i] == null) {
producePosition[i] = "数据";
System.out.println(Thread.currentThread().getName()
+ " 生产了 " + producePosition[i]);
break;
}
}
getCondition.signalAll();
lock.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
setSemaphore.release();
}
}
public void get() {
try {
// System.out.println("get");
getSemaphore.acquire();// 允许同时最多有16个就餐者
lock.lock();
while (isEmpty()) {
System.out.println("消费者在等待");
getCondition.await();
}
for (int i = 0; i < producePosition.length; i++) {
if (producePosition[i] != null) {
System.out.println(Thread.currentThread().getName()
+ " 消费了 " + producePosition[i]);
producePosition[i] = null;
break;
}
}
setCondition.signalAll();
lock.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
getSemaphore.release();
}
}
}

View File

@@ -0,0 +1,24 @@
package ProducerConsumer.test.run;
import ProducerConsumer.service.RepastService;
import ProducerConsumer.extthread.ThreadC;
import ProducerConsumer.extthread.ThreadP;
public class Run {
public static void main(String[] args) throws InterruptedException {
RepastService service = new RepastService();
ThreadP[] arrayP = new ThreadP[60];
ThreadC[] arrayC = new ThreadC[60];
for (int i = 0; i < 60; i++) {
arrayP[i] = new ThreadP(service);
arrayC[i] = new ThreadC(service);
}
Thread.sleep(2000);
for (int i = 0; i < 60; i++) {
arrayP[i].start();
arrayC[i].start();
}
}
}

View File

@@ -0,0 +1,88 @@
package Race;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class TortoiseHareRace {
private static final int RACE_LENGTH = 100; // 赛道长度(米)
private static int tortoisePosition = 0; // 乌龟位置
private static int harePosition = 0; // 兔子位置
private static boolean raceFinished = false; // 比赛是否结束
private static final Object lock = new Object(); // 同步锁
public static void main(String[] args) {
Random random = new Random();
// 乌龟线程:速度慢但稳定
Thread tortoise = new Thread(() -> {
while (!raceFinished) {
synchronized (lock) {
// 乌龟每次移动1-2米
int step = random.nextInt(2) + 1;
tortoisePosition += step;
System.out.println("乌龟前进了" + step + "米,当前位置:" + tortoisePosition + "");
if (tortoisePosition >= RACE_LENGTH) {
raceFinished = true;
System.out.println("乌龟赢得了比赛!");
}
}
try {
TimeUnit.MILLISECONDS.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "乌龟");
// 兔子线程:速度快但会休息
Thread hare = new Thread(() -> {
while (!raceFinished) {
synchronized (lock) {
// 兔子移动速度更快每次移动5-10米
int step = random.nextInt(6) + 5;
harePosition += step;
System.out.println("兔子前进了" + step + "米,当前位置:" + harePosition + "");
if (harePosition >= RACE_LENGTH) {
raceFinished = true;
System.out.println("兔子赢得了比赛!");
}
}
// 兔子有30%的概率会休息
if (random.nextInt(10) < 3) {
int restTime = random.nextInt(600) + 200;
System.out.println("兔子太自信了,休息" + restTime + "毫秒");
try {
TimeUnit.MILLISECONDS.sleep(restTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "兔子");
System.out.println("比赛开始!");
tortoise.start();
hare.start();
try {
tortoise.join();
hare.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("比赛结束!");
System.out.println("最终结果 - 乌龟:" + Math.min(tortoisePosition, RACE_LENGTH) +
"米,兔子:" + Math.min(harePosition, RACE_LENGTH) + "");
}
}

View File

@@ -0,0 +1,78 @@
package RedPacket;
import java.util.Random;
public class AICRedPacketGrabber {
private static int totalMoney = 100;
private static int thread1Money = 0;
private static int thread2Money = 0;
private static final Object lock = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
grabMoney(true);
}
}, "线程1");
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
grabMoney(false);
}
}, "线程2");
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1抢到的总金额: " + thread1Money + "");
System.out.println("线程2抢到的总金额: " + thread2Money + "");
System.out.println("剩余金额: " + totalMoney + "");
}
private static void grabMoney(boolean isThread1) {
Random random = new Random();
while (true) {
synchronized (lock) {
if (totalMoney < 1) {
break;
}
int grabMoney = random.nextInt(3) + 1;
if (grabMoney > totalMoney) {
grabMoney = totalMoney;
}
totalMoney -= grabMoney;
if (isThread1) {
thread1Money += grabMoney;
System.out.println("线程1抢到了" + grabMoney + "元,剩余" + totalMoney + "");
} else {
thread2Money += grabMoney;
System.out.println("线程2抢到了" + grabMoney + "元,剩余" + totalMoney + "");
}
if (totalMoney == 0) {
break;
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

View File

@@ -0,0 +1,91 @@
package RedPacket;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.*;
public class CFRedPacketGrabber {
private static int totalMoney = 100;
private static final Object lock = new Object();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入参与抢红包的线程数: ");
int threadCount = scanner.nextInt();
scanner.close();
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < threadCount; i++) {
final int threadId = i + 1;
Future<Integer> future = executor.submit(new RedPacketGrabber(threadId));
futures.add(future);
}
int[] threadMoney = new int[threadCount];
try {
for (int i = 0; i < threadCount; i++) {
threadMoney[i] = futures.get(i).get();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
for (int i = 0; i < threadCount; i++) {
System.out.println("线程" + (i + 1) + "抢到的总金额: " + threadMoney[i] + "");
}
System.out.println("剩余金额: " + totalMoney + "");
}
static class RedPacketGrabber implements Callable<Integer> {
private final int threadId;
private int moneyGrabbed = 0;
public RedPacketGrabber(int threadId) {
this.threadId = threadId;
}
@Override
public Integer call() {
Random random = new Random();
String threadName = "线程" + threadId;
while (true) {
synchronized (lock) {
if (totalMoney < 1) {
break;
}
int grabMoney = random.nextInt(3) + 1;
if (grabMoney > totalMoney) {
grabMoney = totalMoney;
}
totalMoney -= grabMoney;
moneyGrabbed += grabMoney;
System.out.println(threadName + "抢到了" + grabMoney + "元,剩余" + totalMoney + "");
if (totalMoney == 0) {
break;
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
return moneyGrabbed;
}
}
}

View File

@@ -0,0 +1,82 @@
package RedPacket;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.*;
public class LambdaRedPacketGrabber {
private static int totalMoney = 100;
private static final Object lock = new Object();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入参与抢红包的线程数: ");
int threadCount = scanner.nextInt();
scanner.close();
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < threadCount; i++) {
final int threadId = i + 1;
Future<Integer> future = executor.submit(() -> {
Random random = new Random();
String threadName = "线程" + threadId;
int moneyGrabbed = 0;
while (true) {
synchronized (lock) {
if (totalMoney < 1) {
break;
}
int grabMoney = random.nextInt(3) + 1;
if (grabMoney > totalMoney) {
grabMoney = totalMoney;
}
totalMoney -= grabMoney;
moneyGrabbed += grabMoney;
System.out.println(threadName + "抢到了" + grabMoney + "元,剩余" + totalMoney + "");
if (totalMoney == 0) {
break;
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
return moneyGrabbed;
});
futures.add(future);
}
int[] threadMoney = new int[threadCount];
try {
for (int i = 0; i < threadCount; i++) {
threadMoney[i] = futures.get(i).get();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
for (int i = 0; i < threadCount; i++) {
System.out.println("线程" + (i + 1) + "抢到的总金额: " + threadMoney[i] + "");
}
System.out.println("剩余金额: " + totalMoney + "");
}
}

View File

@@ -0,0 +1,76 @@
package RedPacket;
import java.util.Random;
public class OrderedRedPacketGrabber {
private static int totalMoney = 100;
private static int thread1Money = 0;
private static int thread2Money = 0;
private static boolean isThread1Turn = true;
private static final Object lock = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(() -> grabMoney(true), "线程1");
Thread thread2 = new Thread(() -> grabMoney(false), "线程2");
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1抢到的总金额: " + thread1Money + "");
System.out.println("线程2抢到的总金额: " + thread2Money + "");
System.out.println("剩余金额: " + totalMoney + "");
}
private static void grabMoney(boolean isThread1) {
Random random = new Random();
while (true) {
synchronized (lock) {
while (isThread1Turn != isThread1 && totalMoney >= 1) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (totalMoney < 1) {
lock.notifyAll();
break;
}
int grabMoney = random.nextInt(3) + 1;
if (grabMoney > totalMoney) {
grabMoney = totalMoney;
}
totalMoney -= grabMoney;
if (isThread1) {
thread1Money += grabMoney;
System.out.println("线程1抢到了" + grabMoney + "元,剩余" + totalMoney + "");
} else {
thread2Money += grabMoney;
System.out.println("线程2抢到了" + grabMoney + "元,剩余" + totalMoney + "");
}
isThread1Turn = !isThread1Turn;
lock.notify();
if (totalMoney == 0) {
lock.notifyAll();
break;
}
}
}
}
}

View File

@@ -0,0 +1,67 @@
package RedPacket;
import java.util.Random;
public class RandomRedPacketGrabber {
private static int totalMoney = 100;
private static int thread1Money = 0;
private static int thread2Money = 0;
private static final Object lock = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(() -> grabMoney(true), "线程1");
Thread thread2 = new Thread(() -> grabMoney(false), "线程2");
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1抢到的总金额: " + thread1Money + "");
System.out.println("线程2抢到的总金额: " + thread2Money + "");
System.out.println("剩余金额: " + totalMoney + "");
}
private static void grabMoney(boolean isThread1) {
Random random = new Random();
while (true) {
synchronized (lock) {
if (totalMoney < 1) {
break;
}
int grabMoney = random.nextInt(3) + 1;
if (grabMoney > totalMoney) {
grabMoney = totalMoney;
}
totalMoney -= grabMoney;
if (isThread1) {
thread1Money += grabMoney;
System.out.println("线程1抢到了" + grabMoney + "元,剩余" + totalMoney + "");
} else {
thread2Money += grabMoney;
System.out.println("线程2抢到了" + grabMoney + "元,剩余" + totalMoney + "");
}
if (totalMoney == 0) {
break;
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

View File

@@ -0,0 +1,88 @@
package RedPacket;
import java.util.Random;
import java.util.concurrent.*;
public class ThreadPoolRedPacketGrabber {
private static int totalMoney = 100;
private static final int THREAD_COUNT = 2;
private static final Object lock = new Object();
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
int[] threadMoney = new int[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
final int threadId = i;
executor.submit(new RedPacketGrabber(threadId, threadMoney, latch));
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown();
for (int i = 0; i < THREAD_COUNT; i++) {
System.out.println("线程" + (i + 1) + "抢到的总金额: " + threadMoney[i] + "");
}
System.out.println("剩余金额: " + totalMoney + "");
}
static class RedPacketGrabber implements Runnable {
private final int threadId;
private final int[] threadMoney;
private final CountDownLatch latch;
public RedPacketGrabber(int threadId, int[] threadMoney, CountDownLatch latch) {
this.threadId = threadId;
this.threadMoney = threadMoney;
this.latch = latch;
}
@Override
public void run() {
try {
Random random = new Random();
String threadName = "线程" + (threadId + 1);
while (true) {
synchronized (lock) {
if (totalMoney < 1) {
break;
}
int grabMoney = random.nextInt(3) + 1;
if (grabMoney > totalMoney) {
grabMoney = totalMoney;
}
totalMoney -= grabMoney;
threadMoney[threadId] += grabMoney;
System.out.println(threadName + "抢到了" + grabMoney + "元,剩余" + totalMoney + "");
if (totalMoney == 0) {
break;
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
} finally {
latch.countDown();
}
}
}
}