买票
package com.example.demo.hmjuc.day3;
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
public class Test1 {
public static void main(String[] args) {
while (true) {
TicketWindow ticketWindow = new TicketWindow(2000);
Vector<Thread> objects = new Vector<>();
AtomicInteger atomicInteger = new AtomicInteger(0);
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(() -> {
int count = new Random().nextInt(5) + 1;
int sale = ticketWindow.sale(count);
atomicInteger.addAndGet(sale);
});
thread.start();
objects.add(thread);
}
objects.forEach(thread -> {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
int i = 2000 - atomicInteger.get();
int ticket = ticketWindow.getTicket();
if (i != ticket) {
System.out.println(2000 - atomicInteger.get());
System.out.println("ticketWindow.getTicket() = " + ticket);
System.out.println("出现了线程安全问题 ");
break;
}
}
}
}
class TicketWindow {
private int ticket;
public int getTicket() {
return ticket;
}
public void setTicket(int ticket) {
this.ticket = ticket;
}
public TicketWindow(int ticket) {
this.ticket = ticket;
}
public synchronized int sale(int num) {
if (ticket >= num) {
ticket -= num;
return num;
} else {
return 0;
}
}
}
转账
package com.example.demo.hmjuc.day3;
import java.util.Random;
public class Test2 {
public static void main(String[] args) throws InterruptedException {
while (true) {
Account account1 = new Account(1000);
Account account2 = new Account(1000);
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 100; i++) {
account1.transfer(account2, new Random().nextInt(100) + 1);
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 100; i++) {
account2.transfer(account1, new Random().nextInt(100) + 1);
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
int i = account1.getMoney() + account2.getMoney();
System.out.println("i = " + i);
if (i != 2000) {
break;
}
}
}
}
class Account {
private int money;
public Account(int money) {
this.money = money;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public void transfer(Account target, int money) {
synchronized (Account.class) {
if (this.money >= money) {
this.setMoney(this.getMoney() - money);
target.setMoney(target.getMoney() + money);
}
}
}
}
|