public class TicketDemo2 {
public static void main(String[] args) {
Ticket1 t = new Ticket1();
Thread th1 = new Thread(t);
Thread th2 = new Thread(t);
th1.start();
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();}
t.b = false;
th2.start();
}
}
class Ticket1 implements Runnable{//extends Thread{
private static int tick = 100;
boolean b = true;
public void run(){
if(b){
while(true){
synchronized (Ticket1.class) {
if(tick>0){
try {
Thread.sleep(10);
} catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" ..code : " +tick --);
}
}
}
}else{
while(true){
show();
}
}
}
public static synchronized void show (){
if(tick>0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" ..show.... : " +tick --);
}
}
}
在这个例子里用了Ticket1.class锁,类型为.class |