线程

线程

/*
 * 实现多线程的步骤 
 * 步骤:
 * 定义类继承 Thread
 * 重写 run 方法
 * 把新线程要做的事写在 run 方法中
 * 创建线程对象
 * 开启新线程 start , 内部会自动执行 run 方法
 */

public class Demo1_Thread {
 public static void main(String[] args) {
  // 创建 MyThread

  MyThread mt = new MyThread();
  // mt.run();
  mt.start();

  for (int i = 0; i < 4000; i++) {
   System.out.println(i);
  }

 }
}

public class MyThread extends Thread {
 @Override
 public void run() {
  // 需要做的事

  for (int i = 0; i < 4000; i++) {
   System.out.println("mt-------" + i);
  }
 }
}
还有其他的方法请参看java.lang.Thread里的方法

模拟售票系统

//继承Thread

public class TicketSell extends Thread {
 // 成员变量 票
 static int num = 100;
 public TicketSell() {
 }
 public TicketSell(String name) {
  super(name);
 }
 @Override
 public void run() {
  // 卖票
  while (true) {

//加同一把锁实现同步
   synchronized (TicketSell.class) {
   // 停下来
   System.out.println( getName()  );

//判断票数
   if (num <= 0) {
    break;
   }
    try {

//这里会引发异常,是编译时异常,需要try..catch处理,不让编译不通过,大笑
     Thread.sleep(10);
     System.out.println(getName() + "正在出售第" + num-- + " 张票");
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }
 }
}

public class SellDemo {
 public static void main(String[] args) {

  TicketSell t1 = new TicketSell("窗口1");
  TicketSell t2 = new TicketSell("窗口2");
  TicketSell t3 = new TicketSell("窗口3");
  TicketSell t4 = new TicketSell("窗口4");

  t1.start();
  t2.start();
  t3.start();
  t4.start();

 }
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值