方式1
package example;
public class example11 extends Thread{
static int num=20;
public example11(String name) {
super(name);
}
public void run(){
while(num>0){
synchronized(example11.class){
if(num<1){
break;
}
System.out.println(getName()+"还剩余"+num+"票");
num--;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
example11 st=new example11("窗口1");
st.start();
example11 st1=new example11("窗口2");
st1.start();
example11 st2=new example11("窗口3");
st2.start();
}
}
方式2
package example;
public class example12 implements Runnable{
static int num =20;
public void run() {
while(num>0){
synchronized (this) {
if(num<1){
break;
}
System.out.println(Thread.currentThread().getName()+"还剩余"+num+"票");
num--;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
example12 st=new example12();
Thread th1=new Thread(st, "窗口1");
th1.start();
Thread th2=new Thread(st, "窗口2");
th2.start();
Thread th3=new Thread(st, "窗口3");
th3.start();
}
}
方式3
package example;
public class example13 {
static int num = 20;
public static synchronized void tickets() {
if (num >0) {
System.out.println(Thread.currentThread().getName() + "还剩余" + num + "票");
num--;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
while (num > 0) {
tickets();
}
}
}, "窗口1").start();
new Thread(new Runnable() {
public void run() {
while (num > 0) {
tickets();
}
}
}, "窗口2").start();
new Thread(new Runnable() {
public void run() {
while (num > 0) {
tickets();
}
}
}, "窗口3").start();
}
}