package com.itheima.threaddemo11;
public class MyRunable implements Runnable{
private static int ticketCount=100;
@Override
public void run() {
while (true){
if ("窗口一".equals(Thread.currentThread().getName())){
//同步方法
boolean result = false;
try {
result = synchronizedMethod();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (result){
break;
}
}
if ("窗口er".equals(Thread.currentThread().getName())){
//同步代码块
synchronized (MyRunable.class){
if (ticketCount==0){
break;
}else {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticketCount--;
System.out.println(Thread.currentThread().getName()+"在卖票,还剩下"+ticketCount+"张票");
}
}
}
}
}
private static synchronized boolean synchronizedMethod() throws InterruptedException {
if (ticketCount==0){
return true;
}else {
Thread.sleep(10);
ticketCount--;
System.out.println(Thread.currentThread().getName()+"在卖票,还剩下"+ticketCount+"张票");
return false;
}
}
}
package com.itheima.threaddemo11;
public class Demo {
public static void main(String[] args) {
MyRunable mr=new MyRunable();
Thread t1=new Thread(mr);
Thread t2=new Thread(mr);
t1.setName("窗口一");
t2.setName("窗口二");
t1.start();
t2.start();
}
}