日期:2014-05-20 浏览次数:20755 次
public class MyThread extends Thread{
private static int ticketNum = 0;
public MyThread(String name){
super(name);
}
public void run(){
while(ticketNum<1000){
print();
}
}
public synchronized void print(){
MyThread.ticketNum = 1+MyThread.ticketNum;
System.out.println(this.getName()+"卖票一张,编号:\t"+MyThread.ticketNum);
}
}
MyThread mt=new MyThread("mt");
Thread t1=new Thread(mt,"窗口1");// 四个线程运行同一段代码,同步对象是一个mt.
Thread t2=new Thread(mt,"窗口2");
Thread t3=new Thread(mt,"窗口3");
Thread t4=new Thread(mt,"窗口4");
t1.start();
t2.start();
t3.start();
t4.start();
public class MyThread extends Thread {
private static int ticketNum = 0;
public MyThread(String name) {
super(name);
}
public void run() {
while (ticketNum < 1000) {
print();
}
}
public synchronized void print() {
MyThread.ticketNum = 1 + MyThread.ticketNum;
System.out.println(this.getName() + "卖票一张,编号:\t" + MyThread.ticketNum);
}
public static void main(String[] args) {
new MyThread("").start();
}
}