学习过程观看视频:[狂神说Java]
https://www.bilibili.com/video/BV1V4411p7EF?p=3
欢迎大家支持噢,很良心的老师了!
1、买火车票
package com.zjl;
/**
* Created by zjl
* 2020/11/17
**/
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"老师").start();
new Thread(buyTicket,"学生").start();
new Thread(buyTicket,"黄牛党").start();
}
}
class BuyTicket implements Runnable{
private int ticketNum = 10;
Boolean flag = true; //外部停止方式
@Override
public void run() {
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
if(ticketNum>0) {
//买票
System.out.println(Thread.currentThread().getName() + "买到了第" + ticketNum-- + "张票");
//模拟延时
Thread.sleep(100);
}else {
flag = false;
}
}
}
结果:
2、两个人在同一个账户同时取钱
package com.zjl;
/**
* Created by zjl
* 2020/11/17
**/
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account = new Account(100, "结婚基金");
Drawding you = new Drawding(account, 50, "你");
Drawding grilFriend = new Drawding(account, 100, "女朋友");
you.start();
grilFriend.start();
}
}
//账户
class Account{
int money; //余额
String name; //卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
class Drawding extends Thread{
Account account; //账户
int drawingMoney; //取多少钱
//这个值是算出来的
int nowMoney; //现在手里有多少钱
public Drawding(Account account,int drawingMoney,String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {
//判断账户里面的钱够不够
if(account.money - drawingMoney <0){
System.out.println(Thread.currentThread().getName() + "取钱时,卡内余额不足.............");
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 你取的钱
account.money = account.money - drawingMoney;
//你手里的钱 = 你手里的钱 + 你取的钱
nowMoney = nowMoney + drawingMoney;
//打印余额
System.out.println(account.name + "余额为:" + account.money);
//打印手里的钱
System.out.println(Thread.currentThread().getName() + "手里的钱:" + nowMoney);
}
}
结果:
3、list集合
package com.zjl;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zjl
* 2020/11/17
**/
public class UnsafeLsit {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}