您的位置:首页 > 编程语言 > Java开发

java中的线程同步问题 模拟出售火车票

2015-09-03 12:57 796 查看
/*

 功能:模拟火车售票窗口

 Thread.currentThread().getName()//获取到当前线程的名称

 1.解决所有线程共享 tickets。

 解决思路:①将tickets的数据类型改为static。创建了3个窗口, 每一个窗口代表一个线程。

                    ② 创建一个主窗口对象,创建三个线程对象,分别表示3个线程,传入相同的参数(窗口对象)。

 2.解决同一张票被卖出去多次。(程序的并发执行造成的,多个线程同时访问tickets)

 解决思路:(保证其原子性)当a线程在执行某段代码的时候,其他线程必须等待a执行完之后才能执行这段代码。

                      在需要同步的代码段上加入synchronized (this){}//对象锁 将要同步的代码块包起来

 */

//售票主窗口

class TicketWindows implements Runnable {
private int tickets = 2000;// 总票数

public void run() {
while (true) {
//if else 要保证其原子行 同步代码块
synchronized (this) {
if (tickets > 0) {
// 显示售票信息
System.out.println(Thread.currentThread().getName()
+ "正在售票中   ....还剩" + tickets + "张票");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
tickets--;
} else {
// 退出售票窗口
break;
}
}
// 判断是否还有票
}
}

}

public class TestTickets {

public static void main(String[] args) {
/*
 ///创建了3个窗口 每一个窗口代表一个线程

                      TicketWindows tWindows1=new TicketWindows();

      TicketWindows tWindows2=new TicketWindows(); 

                      TicketWindows tWindows3=new TicketWindows(); 

                      Thread thread1=new Thread(tWindows1);

     Thread thread2=new Thread(tWindows2);

                     Thread thread3=newThread(tWindows3);

                     thread1.start(); 

                     thread2.start();

                     thread3.start();

*/
TicketWindows tWindows1 = new TicketWindows();
Thread thread1 = new Thread(tWindows1);
Thread thread2 = new Thread(tWindows1);
Thread thread3 = new Thread(tWindows1);
thread1.start();
thread2.start();
thread3.start();

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息