java中多个窗口同时买票的并发三种安全实现方式

1.线程实现runable接口(同步中的this可以为任一相同的对象)

首先介绍线程中常用的几个方法如下:

void start()            使该线程开始执行;Java虚拟机调用该线程的 run 

static ThreadcurrentThread()    返回对当前正在执行的线程对象的引用。

StringgetName()           返回该线程的名称。

static voidsleep(long millis)     在指定的毫秒数内让当前正在执行的线程休眠

代码示例:

publicclass ThreadDemo {

   publicstaticvoid main(String[]args) {

      SaleTickets window = new SaleTickets();

      new Thread(window,"窗口1").start();

      new Thread(window,"窗口2").start();

      new Thread(window,"窗口3").start();

      new Thread(window,"窗口4").start();

   }

}

 

class SaleTickets implementsRunnable {

   private int tickets = 100;

 

   publicvoid run() {

      while (true) {

          synchronized (this) {

             try {

                Thread.sleep(20);

             } catch(InterruptedException e) {

                e.printStackTrace();

             }

             if (tickets > 0) {

                 System.out.println(Thread.currentThread().getName()+ "正在发售第" + (101 - tickets) +"张票");

             } else {

                break;

             }

             tickets--;

          }

      }

   }

}

2.synchronized修饰同步方法,不允许并发。

代码示例:

public class ThreadDemo {
	public static void main(String[] args) {
		SaleTickets window = new SaleTickets();
		new Thread(window, "窗口1").start();
		new Thread(window, "窗口2").start();
		new Thread(window, "窗口3").start();
		new Thread(window, "窗口4").start();
	}
}

class SaleTickets implements Runnable {
	private int tickets = 100;

	public void run() {
		while (true) {
			sale();
			if (tickets < 0) {
				break;
			}
		}
	}

	synchronized public void sale() {
		try {
			Thread.sleep(20);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if (tickets > 0) {
	           System.out.println(Thread.currentThread().getName() + "正在发售第" + (101 - tickets) + "张票");
		}
		tickets--;
	}
}

3.可重入锁机制。

Lock是个抽象类,所以要获取同步锁必须通过其子类ReentrantLock来获得实例

ReentrantLock lock = newReentrantLock();

常用方法:

void lock()    获取锁。

void unlock()   试图释放此锁。

代码示例:

import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {

	public static void main(String[] args) {
		SaleTicket window = new SaleTicket();
		new Thread(window, "窗口1").start();
		new Thread(window, "窗口2").start();
		new Thread(window, "窗口3").start();
		new Thread(window, "窗口4").start();
	}

}

class SaleTicket implements Runnable {
	private int tickets = 100;
	ReentrantLock lock = new ReentrantLock();

	public void run() {
		while (true) {
			Sale();
			if (tickets <= 0) {
				break;
			}
		}
	}

	public void Sale() {
		lock.lock();
		try {
			if (tickets > 0) {
			System.out.println(Thread.currentThread().getName() + "正在发售第" + tickets + "票");
				Thread.sleep(30);
				tickets--;
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}

	}
}


你可能感兴趣的:(javaSE基础)