JAVA多线程-synchronized的作用

在多线程运行中,两个程序如果同时调用一个资源,会容易出现错误,如下面代码:

一个图书管理账单。

class Booking{
	private int amount=90;
	public void sale(int num){
		if(num<=amount){
			System.out.println(" 预定 "+num+" 件 ");
			try{
				Thread.sleep(10);
			}
			catch(Exception e){
				e.printStackTrace();
			}
			amount=amount-num;
		}
		else {
			System.out.println("剩余的数量不够,无法预定 ");
		}
		System.out.println(" 还剩 "+amount+"件");
	}
}
class BookingTest implements Runnable{
	Booking bt;
	int num;
	BookingTest(Booking bt,int num){
		this.bt=bt;
		this.num=num;
		new Thread(this).start();
	}
	public void run() {
		bt.sale(num);
	}
	
}
public class BuyItem {
public static void main(String[] args) {
	Booking c1=new Booking();
	new BookingTest(c1,60);
	new BookingTest(c1,70);
}
}

其中两个线程公用线程c1一个资源,所以就会出现错误,运行结果可能会出现:

 预定 70 件 
 预定 60 件 
 还剩 20件
 还剩 -40件

要解决这个问题就要用到synchronized这个修饰词,被synchronized修饰的方法一但被一个线程获取,那只有等这个线程释放了才会被其他线程获取。

synchronized有几种用法:

1:synchronized 方法声明{方法体}

2:方法声明:{synchronized(obj){方法体}}

其中如果obj是this,这两者等效。

上述问题如下解决后:

class Booking{
	private int amount=90;
	public synchronized void sale(int num){
		if(num<=amount){
			System.out.println(" 预定 "+num+" 件 ");
			try{
				Thread.sleep(10);
			}
			catch(Exception e){
				e.printStackTrace();
			}
			amount=amount-num;
		}
		else {
			System.out.println("剩余的数量不够,无法预定 ");
		}
		System.out.println(" 还剩 "+amount+"件");
	}
}
class BookingTest implements Runnable{
	Booking bt;
	int num;
	BookingTest(Booking bt,int num){
		this.bt=bt;
		this.num=num;
		new Thread(this).start();
	}
	public void run() {
		bt.sale(num);
	}
	
}
public class BuyItem {
public static void main(String[] args) {
	Booking c1=new Booking();
	new BookingTest(c1,60);
	new BookingTest(c1,70);
}
}

运行结果如下:

扫描二维码关注公众号,回复: 2241638 查看本文章

 预定 60 件 
 还剩 30件
剩余的数量不够,无法预定 
 还剩 30件

我们发现问题解决了。

参考书籍:《JAVA语言程序设计教程》
 

猜你喜欢

转载自blog.csdn.net/king8611/article/details/81071941