java100-008:.利用多线程模拟抢票(线程不安全,线程安全)

1.利用多线程实现抢票(线程不安全)

package java02;
/**
 *   我的java每天100行代码008
 *  利用多线程实现抢票(线程不安全)
 * @author Administrator
 *
 */
public class java0081 {
	public static void main(String[] args) {
		
		Web12306 w = new Web12306();
		
		Thread t = new Thread(w,"小狗");
		t.start();
		
		Thread t1 = new Thread(w,"小猫");
		t1.start();
		
		Thread t2 = new Thread(w,"小猪");
		t2.start();
	}

}

class Web12306 implements Runnable{
	private int ticketNums = 99;
	
	public void run(){
		while(true) {
			if(ticketNums<0) {
				break;
			}
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+"-->"+ticketNums--);
		}
	}
}

2.利用多线程实现抢票(利用线程同步,保证线程安全)

package java02;
/**
 *   我的java每天100行代码008
 *  利用多线程实现抢票(利用线程同步,保证线程安全)
 * @author Administrator
 *
 */
public class java0083 {
	public static void main(String[] args) {
		
		Web w = new Web();
		
		Thread t = new Thread(w,"小狗");
		t.start();
		
		Thread t1 = new Thread(w,"小猫");
		t1.start();
		
		Thread t2 = new Thread(w,"小猪");
		t2.start();
	}
}

class Web implements Runnable{
	private int ticketNums = 99;
	//利用关键字 synchronized 实现线程同步,锁机制
	//这里是同步方法,也可利用 synchronized(){ } 同步块
	public synchronized void run(){
		while(true) {
			if(ticketNums<=0) {
				break;
			}
			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+"-->"+ticketNums--);
		}
	}
}

你可能感兴趣的:(java100)