同步方法-买票的例子:
package com.kaka.thread;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
public class BuyTicket {
public static void main(String[] args) {
BuyT buyT=new BuyT();
new Thread(buyT,"小明").start();
new Thread(buyT,"老师").start();
new Thread(buyT,"黄牛").start();
}
}
class BuyT implements Runnable{
private int ticketNum=10;
boolean flag=true;
@Override
public void run() {
//买票
while(flag){
buy();
}
}
//synchronized 同步方法 锁的是this
private synchronized void buy(){
if (ticketNum<=0){
System.out.println("没票了!");
flag=false;
}
else{
System.out.println(Thread.currentThread().getName()+"抢到了第"+ticketNum--+"张票");
}
}
}
同步块-银行取钱的例子:
package com.kaka.thread;
//两个人去银行取钱,操作同一个账户
public class TestDrawing {
public static void main(String[] args) {
Account account=new Account("结婚基金",200);
new Drawing(account,50,"wife").start();
new Drawing(account,10,"husband").start();
}
}
//账户
class Account{
String accountName;
int leftMoney;
public Account(String name, int leftMoney) {
this.accountName = name;
this.leftMoney = leftMoney;
}
}
//银行模拟取款
class Drawing extends Thread{
Account account;
int drawingMoney;
String name;//取钱人的名字
int nowMoney=0;
public Drawing(Account account,int drawingMoney, String name){
this.account=account;
this.drawingMoney=drawingMoney;
this.name=name;
}
@Override
public void run() {
//同步块
synchronized (account){
//判断有没有钱
if(account.leftMoney<drawingMoney){
System.out.println(account.accountName+"里钱不够,无法取钱");
}else{
account.leftMoney=account.leftMoney-drawingMoney;
nowMoney=nowMoney+drawingMoney;//你手里的钱=取出的钱
}
System.out.println(name+"取走了:"+nowMoney);
System.out.println(account.accountName+"账户余额为:"+account.leftMoney);
}
}
}