2021-09-12
作者:互联网
标@Java多线程初次接触synchronize
package tiket;
import java.nio.channels.SeekableByteChannel;
public class Ticket {
public static void main(String []args){
Sell1 sell1 = new Sell1();
new Thread(sell1).start();
new Thread(sell1).start();
new Thread(sell1).start();
}
}
class Sell1 implements Runnable{
private int ticket = 100;
private boolean loop = true;
public synchronized void m(){//同步方法,在同一时刻只能有一个线程来执行run方法。
if(ticket <= 0){
System.out.println("票卖完了!");
loop = false;
return;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("窗口:" + Thread.currentThread().getName() + " 卖出一张" + "还剩:" + (--ticket));
}
@Override
public void run(){
while(loop){
m();
}
}
}
标签:12,Thread,09,start,2021,sell1,new,public,Sell1 来源: https://blog.csdn.net/qq_45371665/article/details/120255319