public class SellTick implements Runnable{
private int tick = 100;//有100张票
@Override
public void run() {
while (true){
if (tick == 0){
break;
}
tick--;
System.out.println(Thread.currentThread().getName()+"正在卖第"+tick+"张票");
}
}
}
public class Test {
public static void main(String[] args) {
SellTick st = new SellTick();
//创建三个线程,线程名为猫眼、美团、抖音
new Thread(st, "猫眼").start();
new Thread(st, "美团").start();
new Thread(st, "抖音").start();
}
}
②当然我们这种数据太少了,不好观察,于是我们可以加入sleep方法来放大问题;
public class SellTick implements Runnable{
private int tick = 100;//有100张票
@Override
public void run() {
while (true){
if (tick == 0){
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
tick--;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName()+"正在卖第"+tick+"张票");
}
}
}
public class SellTick implements Runnable{
private int tick = 100;//有100张票
private Object o = new Object();//锁对象定义在外面,确保大家使用的都是同一个锁
@Override
public void run() {
while (true){
synchronized (o) {
if (tick == 0){
break;
}
tick--;
System.out.println(Thread.currentThread().getName()+"正在卖第"+tick+"张票");
}
}
}
}
(2)采用(同步方法) --->一般不用这个方法
格式:
修饰符 synchronized 返回值类型 方法名(参数列表){
}
public class SellTick implements Runnable{
private int tick = 100;//有100张票
private Object o = new Object();//锁对象定义在外面,确保大家使用的都是同一个锁
@Override
public synchronized void run() {
while (true){
if (tick == 0){
break;
}
tick--;
System.out.println(Thread.currentThread().getName()+"正在卖第"+tick+"张票");
}
}
}
public class SellTick implements Runnable{
private int tick = 100;//有100张票
private Object o = new Object();//锁对象
@Override
public void run() {
synchronized (o) {
while (true){
if (tick == 0){
break;
}
tick--;
System.out.println(Thread.currentThread().getName()+"正在卖第"+tick+"张票");
}
}
}
}