Java多线程机制(实现Runnable接口模拟售票)

源地址

java中我们想要实现多线程常用的有两种方法,继承Thread 类和实现Runnable 接口
  • 有经验的程序员都会选择实现Runnable接口 ,其主要原因有以下两点:

首先,java只能单继承,因此如果是采用继承Thread的方法,那么在以后进行代码重构的时候可能会遇到问题,因为你无法继承别的类了。
其次,如果一个类继承Thread,则不适合资源共享。但是如果实现了Runable接 口的话,则很容易的实现资源共

Synchronize关键字

synchronized,同步可以修饰代码块和方法,多线程时相当于互斥锁

package com.zzti.edu.thread;

/**
* @Classname TicketWindow
* @Author jdq8576
* @Date 2019/4/1 10:02
**/
package com.zzti.edu.thread;

/**
* @Classname TicketWindow
* @Author jdq8576
* @Date 2019/4/1 10:02
**/
public class TicketWindow implements Runnable{

  public  int num = 100;// 被所有线程共有,

  @Override
  public  void run() {
      while (true) {
          method();
      }
  }
  private synchronized void method() {
          if (num >= 1) {
              System.out.println(Thread.currentThread().getName() + ": " + num--);
              try {
                  Thread.sleep(100);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
      }
  }
}
package com.zzti.edu.thread;

/**
* @Classname Test
* @Author jdq8576
* @Date 2019/4/1 10:08
**/
public class Test {
  public static void main(String[] args){

      TicketWindow ticketWindow = new TicketWindow();

      Thread threadOne = new Thread(ticketWindow);
      threadOne.setName("WindowOne");
      Thread threadTwo = new Thread(ticketWindow);
      threadTwo.setName("WindowTwo");
      Thread threadThree = new Thread(ticketWindow);
      threadThree.setName("WindowThree");


      threadThree.start();
      threadOne.start();
      threadTwo.start();
  }
}

猜你喜欢

转载自blog.csdn.net/jdq8576/article/details/88947259