多线程卖票实例

java多线程实现方式主要有两种:继承Thread类、实现Runnable接口;

package com.test.thread;

import java.util.List;

public class salePicketThread extends Thread {

	private List ps;
	
	public salePicketThread(List ps,String name) {
		this.ps = ps;
		setName(name);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		while(ps.size() != 0){
			
			synchronized (ps) {//同步
				if(ps.size() != 0){//双重锁
				String p = ps.remove(0);
				System.out.println(getName()+"卖出了"+p);
				}
			}//wait()强制睡眠等待,notfiy()通知唤醒
			
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		
		
	}
}

package com.test.thread;

import java.util.List;

public class salePicketRunnable implements Runnable {

    private List ps;
    private String name;
	
	public salePicketRunnable(List ps,String name) {
		this.ps = ps;
		this.name = name;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
            while(ps.size() != 0){
			
			synchronized (ps) {
				if(ps.size() != 0){//双重锁
				String p = ps.remove(0);
				System.out.println(name+"卖出了"+p);
				}
			}//wait()强制睡眠等待,notfiy()通知唤醒
			
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

}

package com.test.thread;

import java.util.ArrayList;
import java.util.List;

public class demos {

	public static void main(String[] args) {

		List ps = new ArrayList();

		for (int i = 1; i <=30; i++) {
			ps.add("第"+i+"张电影票");	
		}
		//继承Thread类的取票
		salePicketThread s1 = new salePicketThread(ps,"東售票处1》");
		s1.start();
		salePicketThread s2 = new salePicketThread(ps,"西售票处2》");
		s2.start();
		//实现Runnable接口的取票
		salePicketRunnable run1 = new salePicketRunnable(ps, "南售票处3>>");
		new Thread(run1).start();
		salePicketRunnable run2 = new salePicketRunnable(ps, "北售票处4>>");
		new Thread(run2).start();
	}
}


你可能感兴趣的:(JAVA)