1. 程式人生 > >執行緒同步的三種實現方式

執行緒同步的三種實現方式

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();
			}
		}
	}
}