package com.company.test4;
public class ThreadMain {
public static void main(String[] args) {
ThreadTest1 sa = new ThreadTest1();
//开启3个线程
Thread th1 = new Thread(sa, "用户1 ");
Thread th2 = new Thread(sa, "用户2 ");
Thread th3 = new Thread(sa, "用户3 ");
th1.start();
th2.start();
th3.start();
}
}
class ThreadTest1 implements Runnable {
private static int tick = 100;//火车票
//只要加入关键字同步线程,就只有一个线程,去掉关键字,多个线程就会开启
@Override
public synchronized void run() {
String name = Thread.currentThread().getName();
while (tick > 0) {
try {
{
Thread.sleep(100);
System.out.println(name + "购票时候还剩余" + tick--);
tick = tick - 1;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
问题1: 线程run()方法上未添加关键字synchronized
2、当去掉run()方法前的关键字synchronized()时候,就会出现3个线程对象
synchronized 同步,那得等一下线程运行完成了才能出来哦。要把synchronized放在循环语句内部实现。
被synchronized锁住的代码块或者方法,别人进不来,只有当synchronized锁住的代码块或者方法执行完毕时别的线程才有机会执行
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632