疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

Java线程同步--卖票问题


 

  线程同步方法:

  (1)、同步代码块,格式:

  synchronized (同步对象){

  //同步代码

  }

  (2)、同步方法,格式:

  在方法前加synchronized修饰

  问题:

  多个人同时买票。

  1、资源没有同步。

  package thread;

  public class Tickets implements Runnable {

  private int count = 5;

  @Override

  public void run() {

  for (int i = 0; i < 10; ++i) {

  if (count > 0) {

  try {

  Thread.sleep(1000);

  } catch (InterruptedException e) {

  e.printStackTrace();

  }

  System.out.println(count--);

  }

  }

  }

  public static void main(String[] args) {

  Tickets tickets=new Tickets();

  Thread t1=new Thread(tickets);

  Thread t2=new Thread(tickets);

  Thread t3=new Thread(tickets);

  t1.start();

  t2.start();

  t3.start();

  }

  }

  运行结果:

  5

  3

  4

  2

  2

  1

  很明显结果是错的。

  2、同步代码块

  run方法中进行同步,也就是对共享资源(票数、count)进行同步

  package thread;

  public class Tickets implements Runnable {

  private int count = 5;

  @Override

  public void run() {

  for (int i = 0; i < 10; ++i) {

  synchronized (this) {

  if (count > 0) {

  try {

  Thread.sleep(1000);

  } catch (InterruptedException e) {

  e.printStackTrace();

  }

  System.out.println(count--);

  }

  }

  }

  }

  public static void main(String[] args) {

  Tickets tickets = new Tickets();

  Thread t1 = new Thread(tickets);

  Thread t2 = new Thread(tickets);

  Thread t3 = new Thread(tickets);

  t1.start();

  t2.start();

  t3.start();

  }

  }

  3、同步方法

  package thread;

  public class Tickets implements Runnable {

  private int count = 5;

  @Override

  public void run() {

  for (int i = 0; i < 10; ++i) {

  sale();

  }

  }

  public synchronized void sale() {

  if (count > 0) {

  try {

  Thread.sleep(1000);

  } catch (InterruptedException e) {

  e.printStackTrace();

  }

  System.out.println(count--);

  }

  }

  public static void main(String[] args) {

  Tickets tickets = new Tickets();

  Thread t1 = new Thread(tickets);

  Thread t2 = new Thread(tickets);

  Thread t3 = new Thread(tickets);

  t1.start();

  t2.start();

  t3.start();

  }

  }