同步方法
public class SafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"Tenton").start();
new Thread(station,"East").start();
new Thread(station,"黄牛党").start();
}
}
class BuyTicket implements Runnable{
//票数
private int ticket = 10;
//外部停止方式
boolean flag = true;
@Override
public void run() {
//买票
while (flag){
try {
buy();
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void buy() {
//判断是否有票
if (ticket <= 0){
flag = false;
return;
}
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticket-- +"张票");
}
}
同步块
public class SafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
//锁的对象就是变化的量,需要执行增删改的对象
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}