Java 【线程同步】—— 同步锁 { }

synchronized
public class test {
    
    
	public static void main(String[] args){
    
    
		MyRunnable mr = new MyRunnable();
		Thread t_01 = new Thread(mr);
		Thread t_02 = new Thread(mr);
		t_01.start();
		t_02.start();
	}
}
class MyRunnable implements Runnable {
    
    
	private int ticket = 10;
	private Object obj = new Object();
	public void run(){
    
    
		for(int i=0;i<300;i++){
    
    
			if(ticket>0){
    
    
				synchronized(obj/* this */){
    
    
					ticket--;
					try {
    
    
						// 当使用sleep方法的时候
						// 线程不会丢失任何显示器的所有权
						Thread.sleep(1000);
					}catch(InterruptedException e){
    
    
						System.out.println(e);
					}
					System.out.println("您购买的票剩余:"+ticket+"张");
				}
			}
		}
	}
}
同步方法
public class test {
    
    
	public static void main(String[] args){
    
    
		MyRunnable mr = new MyRunnable();
		Thread t_01 = new Thread(mr);
		Thread t_02 = new Thread(mr);
		t_01.start();
		t_02.start();
	}
}
class MyRunnable implements Runnable {
    
    
	private int ticket = 10;
	private Object obj = new Object();
	public void run(){
    
    
		for(int i=0;i<300;i++){
    
    
			method();
		}
	}
	// 同步方法: 同步的对象是当前对象(this)
	private synchronized void method(){
    
    
		if(ticket>0){
    
    
			ticket--;
			try {
    
    
				Thread.sleep(100);
			}catch(InterruptedException e){
    
    
				System.out.println(e);
			}
			System.out.println("您购买的票剩余:"+ticket+"张");
		}
		
	}
}

在这里插入图片描述

Lock 接口
import java.util.concurrent.locks.ReentrantLock;
public class test {
    
    
	public static void main(String[] args){
    
    
		MyRunnable mr = new MyRunnable();
		Thread t_01 = new Thread(mr);
		Thread t_02 = new Thread(mr);
		t_01.start();
		t_02.start();
	}
}
class MyRunnable implements Runnable {
    
    
	private int ticket = 10;
	private Object obj = new Object();
	public void run(){
    
    
		for(int i=0;i<300;i++){
    
    
			method();
		}
	}
	// 互斥锁
	ReentrantLock lock = new ReentrantLock();
	private void method(){
    
    
		lock.lock(); // 加锁
		try{
    
    
			if(ticket>0){
    
    
				ticket--;
				try {
    
    
					Thread.sleep(100);
				}catch(InterruptedException e){
    
    
					System.out.println(e);
				}
				System.out.println("您购买的票剩余:"+ticket+"张");
			}
		}finally{
    
    
			lock.unlock(); // 释放锁
		}
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43921423/article/details/112623497