java多线程--买票(ticket)实验

1.以继承Thread的方式:

package org.sh.diffdemo;

public class MyThread extends Thread {
	private int ticket = 5;
	public void run(){
		for(int i =0;i<10;i++){
			if(this.ticket>0){
				System.out.println("买票:ticket="+this.ticket--);
			}
		}
	}
}

package org.sh.diffdemo;

public class ThreadTicket {
	public static void main(String[] args) {
		MyThread m1 = new MyThread();
		MyThread m2 = new MyThread();
		m1.start();
		m2.start();
	}
}

发现结果买了十张票 但是只有五张票,没有达到共享资源的目的 ,下面使用实现Runnable接口

2.以实现Runnable的方式:

package org.sh.diffdemo1;

public class MyThread implements Runnable {
	private int ticket = 5;
	public void run(){
		for(int i =0;i<10;i++){
			if(this.ticket>0){
				System.out.println("买票:ticket="+this.ticket--);
			}
		}
	}
}

package org.sh.diffdemo1;

public class ThreadTicket {
	public static void main(String[] args) {
		MyThread m1 = new MyThread();
		Thread t1 = new Thread(m1);
		Thread t2 = new Thread(m1);
		t1.start();
		t2.start();
	}
}

虽然是两个线程但是还是只是买了五张票,达到了共享资源的目的了。

在程序中加入延迟:

package org.sh.syndemo;

 class MyThread implements Runnable {
	private int ticket = 5;
	public void run(){
		for(int i =0;i<10;i++){
			if(this.ticket>0){
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("买票:ticket="+this.ticket--);
			}
		}
	}
}

public class SynDemo01 {
	public static void main(String[] args) {
		MyThread m1 = new MyThread();
		Thread t1 = new Thread(m1);
		Thread t2 = new Thread(m1);
		t1.start();
		t2.start();
	}
}

结果:

买票:ticket=5
买票:ticket=5
买票:ticket=4
买票:ticket=4
买票:ticket=3
买票:ticket=2
买票:ticket=1
买票:ticket=0

相信这个结果 大家都知道原因 这里不解释了,对上面的代码进行同步即可

3.线程间的同步

package org.sh.syndemo;

 class MyThread implements Runnable {
	private int ticket = 5;
	public void run(){
		for(int i =0;i<10;i++){
			this.sale();
		}
	}
	public synchronized void sale(){
			if(this.ticket>0){
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("买票:ticket="+this.ticket--);
		}
	}
}

public class SynDemo01 {
	public static void main(String[] args) {
		MyThread m1 = new MyThread();
		Thread t1 = new Thread(m1);
		Thread t2 = new Thread(m1);
		t1.start();
		t2.start();
	}
}


你可能感兴趣的:(java)