同步方法:
package top.xq.thread;
/**
* 类名称 SafeThread
* 说明 使用synchronized关键字来实现方法的线程安全
* 作者 IT小黑
* 日期 2019/10/15 11:02
*/
public class SafeThread implements Runnable {
private Integer tickets = 99;
@Override
public void run() {
buyTickets();
}
private synchronized void buyTickets() {
System.out.println(Thread.currentThread().getName() + " 购买了第:" + tickets-- + "张票");
}
public static void main(String[] args) {
SafeThread safeThread = new SafeThread();
for(int i = 1; i < 20; i++) {
Thread thread = new Thread(safeThread, "线程"+i);
thread.start();
}
Thread threadNew = new Thread(()->{});
try {
threadNew.join()