我们如何在Java中实现线程安全?

Java中的线程安全

  • 在Java的同步概念中引入了线程安全性概念。

  • 当多个人或多个线程同时在同一对象上操作时,可能会出现不一致问题。

  • 通过使用synced关键字,我们可以实现线程安全(即,仅允许一个线程访问特定对象)。

  • 通过使用同步概念,我们可以克服不一致的问题。

  • 借助示例,我们将理解为什么需要线程安全

示例:在预订系统中

  1. 在火车上,我们只有5个空位。

  2. 如果两个人试图在网上订票,每个人想要三个座位。

  3. 当它们两个都有机会但它们中的任何一个都将收到一条消息,提示剩余空位不足。

  • 如果某个方法或块声明为已同步,则一次只允许一个线程在特定对象上执行该方法或块,因此将解决数据不一致问题。

  • 如果线程以此方式一个接一个地执行,我们可以实现数据不一致和线程安全性,但是这会增加线程的等待时间,从而降低性能。

  • 如果我们将方法声明为已同步,则意味着一次只允许一个线程访问该方法,而其余线程可以同时访问非同步方法(即,对同步方法的限制和对非同步方法的限制)。

  • 在同一对象上使用多个线程时,将需要线程安全。在一个线程将处于安全状态时,无需在单个线程中实施。

示例

在下面的示例中,我们将实现同步概念:

class SynchronizeMethodClass{

	public synchronized void fruits( String fruits){
		for(int i=0;i<10;++i){
			System.out.println("I am in fruits method :");
			try{
				Thread.sleep(1000);
			}
			catch(InterruptedException ie){
				System.out.println("Exception occurs");
			}
			System.out.println(fruits);
		}
	}
}

class FirstThread extends Thread{
	SynchronizeMethodClass SMC;
	String fruits;
	FirstThread(SynchronizeMethodClass SMC , String fruits){
		this.SMC = SMC;
		this.fruits = fruits;
	}
	public void run(){
		SMC.fruits(fruits);
	}
}

class SecondThread{
	public static void main(String[] args){
		SynchronizeMethodClass SMC = new SynchronizeMethodClass();
		FirstThread FT  = new FirstThread(SMC,"APPLE");
		FirstThread FTT= new FirstThread(SMC,"Orange");
		FirstThread FTTT = new FirstThread(SMC,"Grapes");
		FirstThread FTTTT = new FirstThread(SMC,"Banana");
		FT.start();
		FTT.start();
		FTTT.start();
		FTTTT.start();
	}
}

输出结果

D:\Java Articles>java SecondThread
I am in fruits method :
Grapes
I am in fruits method :
Grapes
I am in fruits method :
Grapes
I am in fruits method :
Grapes
I am in fruits method :
Grapes
I am in fruits method :
Grapes
I am in fruits method :
Grapes
I am in fruits method :
Grapes
I am in fruits method :
Grapes
I am in fruits method :
Grapes
I am in fruits method :
Banana
I am in fruits method :
Banana
I am in fruits method :
Banana
I am in fruits method :
Banana
I am in fruits method :
Banana
I am in fruits method :
Banana
I am in fruits method :
Banana
I am in fruits method :
Banana
I am in fruits method :
Banana
I am in fruits method :
Banana
I am in fruits method :
Orange
I am in fruits method :
Orange
I am in fruits method :
Orange
I am in fruits method :
Orange
I am in fruits method :
Orange
I am in fruits method :
Orange
I am in fruits method :
Orange
I am in fruits method :
Orange
I am in fruits method :
Orange
I am in fruits method :
Orange
I am in fruits method :
APPLE
I am in fruits method :
APPLE
I am in fruits method :
APPLE
I am in fruits method :
APPLE
I am in fruits method :
APPLE
I am in fruits method :
APPLE
I am in fruits method :
APPLE
I am in fruits method :
APPLE
I am in fruits method :
APPLE
I am in fruits method :
APPLE