线程同步
并发
- 并发:同一个对象被多个线程同时操作:多人同时抢1张票、多人同时在一个账号里取钱
package www.bh.c.threadtest;
public class BuyTickets implements Runnable{
public static void main(String[] args) {
BuyTickets buyTickets = new BuyTickets();
new Thread(buyTickets,"你").start();
new Thread(buyTickets,"我").start();
new Thread(buyTickets,"他").start();
}
private int tickets=10;
boolean flag=true;
@Override
public void run() {
while (flag){
try {
buy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void buy(){
if (tickets<=0){
flag=false;
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+tickets--+"张票");
}
}
package www.bh.c.threadtest;
public class GetMoney {
public static void main(String[] args) {
Account account = new Account(100,"学费");
Drawing you = new Drawing(account, 50, "you");
Drawing yousister = new Drawing(account, 100, "sister");
yousister.start();
you.start();
}
}
class