前两天写了个多线程售票的程序,练习下多线程和同步的概念,把代码贴出来与大家分享!
package test.thread;
class Test implements Runnable {//多线程售票类
station s=new station();
public static void main(String[] args) {
Test test = new Test();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
Thread t3 = new Thread(test);
t1.setName("t1");
t2.setName("t2");
t3.setName("t3");
t1.start();
t2.start();
t3.start();
}
public void run(){
while(s.getTicket()>0){s.sellTicket(Thread.currentThread().getName());
}
}
package test.thread;
public class station {//车站类
private static station instance = null;
private static int ticket=100;
public static synchronized station getInstance(){
if(instance == null)
instance = new station();
return instance;
}
public synchronized void sellTicket(String threadName){
if(ticket>0){
System.out.println("线程 "+threadName+"得到票 "+ticket);
ticket--;
}
}
public static int getTicket() {
return ticket;
}
public static void setTicket(int ticket) {
station.ticket = ticket;
}
}
上面的代码中车站类不必写成单例形式,分析下run方法体中的多线程代码,其中写一个车站卖票的方法,卖票方法中有2个动作,第一步得到票,第二步票数减1,这两个动作不能被多线程打断,所以要放在同步方法体中,在run方法体中s.getTicket()不是同步的方法,就是说可以有多个线程一起执行这个方法,得到当前票数是100,但只有一个线程能够进入到售票的方法中进行售票,然后票数减1,而其他线程进入到售票的方法中,看到的车票是减1后的票数,保持了数据一致,不会出现同一张票卖多次的情况,直至把票卖完!