线程同步的三种实现方式

java线程的同步问题可以通过三种方式实现:

首先创建四个线程:

public class Test01 {
	public static void main(String[] args) {
		//创建接口实现类实例化对象
		Runnable r1 = new TicketRunnableImpl();
		//创建线程
		Thread t1 = new Thread(r1, "窗口一");
		Thread t2 = new Thread(r1, "窗口二");
		Thread t3 = new Thread(r1, "窗口三");
		Thread t4 = new Thread(r1, "窗口四");
		//启动线程
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}

实现方式一:使用synchronized代码块

public class TicketRunnableImpl implements Runnable{
	private int ticketNum = 1000;
	@Override
	public void run() {
		while (ticketNum > 0) {
			//同步代码块
			synchronized (this) {
				//判断
				if (ticketNum > 0) {
					ticketNum--;
					System.out.println(Thread.currentThread().getName() + "售出一张票,剩余:" + ticketNum);
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
实现方式二:使用对象锁

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketRunnableImpl implements Runnable{
	private int ticketNum = 1000;
	//创建锁对象
	Lock lock = new ReentrantLock();
	@Override
	public void run() {
		while (ticketNum > 0) {
			//上锁
			lock.lock();
			//判断
			if (ticketNum > 0) {
				ticketNum--;
				System.out.println(Thread.currentThread().getName() + "售出一张票,剩余:" + ticketNum);
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			//解锁
			lock.unlock();
		}
	}
}
实现方式三:使用同步方法

public class TicketRunnableImpl implements Runnable{
	private int ticketNum = 1000;
	@Override
	public void run() {
		while (ticketNum > 0) {
			sellTickets();
		}
	}
	//同步方法
	public synchronized void sellTickets() {
		//判断
		if (ticketNum > 0) {
			ticketNum--;
			System.out.println(Thread.currentThread().getName() + "售出一张票,剩余:" + ticketNum);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}




你可能感兴趣的:(Java,web)