喜欢研究学习技术,喜欢和志同道合的人交流。 从事测试6年,专职性能3年经验,擅长性能测试,测试框架开发。 励志格言:只要想学习,永远都不会太晚;只要想进步,永远都会有空间。

java 多线程实现购火车票功能

上一篇 / 下一篇  2014-11-06 21:31:38 / 个人分类:java开发技术

实现方式一:继承Thread线程类
public class TestThread2 extends Thread {
 //模拟多个窗口买票的场景
 private static int num=300;
 
 public void run(){
  while(num>0){
   //线程安全问题
   System.out.println(this.getName()+"卖出了第"+num+"号票!");
   num--;
  }
 }
 public static void main(String[] args) {
  TestThread2 tt1=new TestThread2();
  tt1.setName("窗口一:");
  tt1.start();
  
  
  TestThread2 tt2=new TestThread2();
  tt2.setName("窗口二:");
  tt2.start();
  
  TestThread2 tt3=new TestThread2();
  tt3.setName("窗口三:");
  tt3.start();
 }
}
 
方式二:实现runnable接口
public class TestRunble2 implements Runnable{
 //模拟多个窗口买票的场景
 /*
  * 实现Runable接口创建线程的好处:
  * 1、资源共享性比继承Thread类好
  * 2、避免的Java的单继承约束
  *
  * 综上所述:建议使用实现Runable方式创建线程
  */
 private int num=300;
 
 @Override
 public void run() {
  while(num>0){
   //线程安全问题
   System.out.println(Thread.currentThread().getName()+"卖出了第"+num+"号票!");
   num--;
  }
 }
 public static void main(String[] args) {
  TestRunble2 tr=new TestRunble2();
  
  Thread t=new Thread(tr);
  t.setName("-窗口1-:");
  t.start();
  
  Thread t2=new Thread(tr);
  t2.setName("-窗口2-:");
  t2.start();
  
  Thread t3=new Thread(tr);
  t3.setName("-窗口3-:");
  t3.start();
 }
}
 

TAG:

 

评分:0

我来说两句

Open Toolbar