cool hit counter J2SE Fast Forward] - Multithreaded Synchronized_Intefrankly

J2SE Fast Forward] - Multithreaded Synchronized


Copyright: This is an original post by the blogger and may not be reproduced without the blogger's permission. https://blog.csdn.net/huyuyang6688/article/details/44099117

meGoing to the bank with my wife to withdraw money

One day, made a bet with my wife that I now have a total of $5,000 in my bank account and we'll go to the bank and withdraw the money at the same time to see if we can both take out 5,000 。。。。 (PS: The price of the bet: if both can take out 5,000, the 10,000 goes to her for food! If you can only take 5,000, hey, then just use the 5,000 to buy her food ~~~~ Why do you think that's a bit of an odd condition nie? )

Better to act than to be impressed! She took her bankbook to the counter to get, me Take the bank card.ATM mechanically obtained, Found the right time., me When entering a good amount, Keep staring at that.teller simple hands, As he hits enter when everything is ready, me With a swift press of the OK。 end, me ofATM The machine swishes and spits out50 (coll.) Zhang Mao's grandfather, The wife's side also gleefully took5000 It's coming over in bucks.。。。。 “ feed (an animal, baby, invalid etc)~ Wake up.!”

So it was a dream.~~ not work, these potential practicable, me Gotta try it.! Don't disbelieve it., me And verified it with what I just learned about threads!

public class TestDrawMoney implements Runnable {
 	// Note: The context of this example is [multiple] [simultaneous] withdrawals on [the same account]
 	// Withdrawals on unified account danny's account
	Depositor danny = new Depositor();
	public static void main(String[] args) {
		TestDrawMoney test=new TestDrawMoney();
 		// My withdrawal operation is a thread draw1 and my wife's withdrawal operation is a thread draw2
		Thread draw1 = new Thread(test);
		Thread draw2 = new Thread(test);
		draw1.setName(" me");
		draw2.setName(" me (coll.) wife");
 		// Start a thread
		draw1.start();
		draw2.start();
	}
     // Rewrite the run method
	public void run() {
		danny.DrawMoney(5000);
	}
}

 /Savers category
class Depositor {
 	//balance
	private static int deposit = 5000;
 	//Method of withdrawal of money
	public void  DrawMoney(int money) {
		if (money <= deposit) {
 			// Simulation of a bank spitting out money
			System.out.println(Thread.currentThread().getName() + " cash withdrawal: Successful withdrawal!" + money + " primary!");
 			// Mock account debit process
			deposit = deposit - money;
		}else{
			System.out.println(Thread.currentThread().getName()+" cash withdrawal: insufficient balance!");
		}		
	}
}

If the bank withdrawal process is similar to the one above, then one of the threads (e.g. my wife withdrawing money) runs until the "account debit", when the resource potential by another thread( for example me withdraw money) Grab it and run., at this time, The first thread because it has already determined that the account balance is sufficient, And the money has already been given me (coll.) wife, But before the bank debit runs, me The money withdrawal thread preempts the execution, The bank hasn't deducted the money., So in me Fetching money in this thread, The balance is also judged to be sufficient。 Guess what the test showed?? me Both of them really took it out5000!

Unfortunately after learning the mechanism of locks in threads, this dream of getting rich was completely shattered 。。。。

public class TestDrawMoney implements Runnable {
 	// Note: The context of this example is [multiple] [simultaneous] withdrawals on [the same account]
 	// Withdrawal on the account of the unified account danny
	Depositor danny = new Depositor();

	public static void main(String[] args) {
		TestDrawMoney test = new TestDrawMoney();
		//  me The withdrawal operation is a threaddraw1, me The wife's withdrawal operation is also a threaddraw2
		Thread draw1 = new Thread(test);
		Thread draw2 = new Thread(test);
		draw1.setName(" me");
		draw2.setName(" me (coll.) wife");
 		// Start threads
		draw1.start();
		draw2.start();
	}

 	// Rewrite the run method
	public void run() {
		danny.DrawMoney(5000);
	}
}

 // Saver category
class Depositor {
 	// Balance
	private static int deposit = 5000;
 	// Method of withdrawing money
	public void DrawMoney(int money) {
 		synchronized (this) {// Here a lock is added for the entire thread's operation
			if (money <= deposit) {
	 			// Simulation of a bank spitting out money
				System.out.println(Thread.currentThread().getName() + " cash withdrawal: Successful withdrawal!" + money + " primary!");
	 			// Mock account debit process
				deposit = deposit - money;
			} else {
				System.out.println(Thread.currentThread().getName+" cash withdrawal: insufficient balance!");
			}
		}
	}
}

The only difference from the first example is that a lock - synchronized - is added to the DrawMoney() method, so that when a thread runs this method, the object is locked and no other thread can execute the locked code in this method.

The result of the run is that only one person can take out the money: the

perhaps

(The two threads, the one that executes first is able to take out the money, but it is not certain who is first and who is second, so there will be two results. )

Introduction to synchronized

When multiple threads potential When accessing the same resource at the same time, Just consider whether to usesynchronized。synchronized Used to give objects、 approach perhaps Locking of the code block。 Only one thread can execute the locked code at the same time, No other threads will interrupt it, Must wait until the thread currently executing the locked code has finished executing, Only other threads can execute。

The essence of sychronized is. During the execution of the locked method or code, the current object is locked (in the above example, since the current object "danny" is locked, the static variable "deposit" in the current object must also be locked).

Usage of synchronized

1. Modify the method with synchronized, as in the above example, you can directly modify the method of DrawMoney() with synchronized.

	public synchronized void DrawMoney(int money) {
			if (money <= deposit) {
	 			// Simulation of a bank spitting out money
				System.out.println(Thread.currentThread().getName() + " cash withdrawal: Successful withdrawal" + money + " primary!");
	 			// Mock account debit process
				deposit = deposit - money;
			} else {
				System.out.println(Thread.currentThread().getName() + " cash withdrawal: insufficient balance!");
			}
	}

If an object has multiple synchronized methods, as long as one thread accesses one of the synchronized methods, no other thread can access any of the synchronized methods in the object at the same time.

If two threads want to access the method at the same time, then it needs to be accessed in both instance objects. That is, the methods modified by synchronized in different object instances do not interfere with each other.

2、Lock the code with synchronized

As in the second example above, in the method, lock the code with synchronized(this){ //code snippet} that only allows one thread to access at the same moment. At the same moment, no other thread is allowed to access the locked segment of this object. That is, when the execution of this code segment, this current object will be locked, other threads are not allowed to access, until the current thread is finished, other threads can access.

The two uses of synchronized to modify member methods and synchronized(this) have the same meaning.

synchronized potential Problems that will arise

When "locking" a program, it can cause other problems - deadlocks.

For example, now Danny and Maria only have one pair of chopsticks, and the only way they can eat a big meal is to grab two pairs of chopsticks.

public class TestDeadLock2 implements Runnable {
 	public String name;       // Name
 	static Object chopsticks1 = new Object();       / / First Chopsticks
 	static Object chopsticks2 = new Object();       //Second chopstick

	public static void main(String[] args) {
		System.out.println(" Let the chopstick grab begin!");
		TestDeadLock2 test1=new TestDeadLock2();
		TestDeadLock2 test2=new TestDeadLock2();
		test1.name="Danny";
		test2.name="Maria";
		Thread t1=new Thread(test1);
		Thread t2=new Thread(test2);
		t1.start();
		t2.start();
	}

	public void run() {
		if (name.equals("Danny")) {
			synchronized (chopsticks1) {
				try {
 					Thread.sleep(500);// Here, to amplify the effect, let Danny pause when he grabs chopstick 1
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (chopsticks2) {
					System.out.println("Danny Successfully grabbed two chopsticks, He's going to eat.!");
				}
			}
		} else if (name.equals("Maria")) {
			synchronized (chopsticks2) {
				try {
 					Thread.sleep(500);// Here, to amplify the effect, let Maria pause when she grabs Chopsticks 2
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (chopsticks1) {
					System.out.println("Maria Successfully grabbed two chopsticks, She's going to eat.!");
				}
			}
		}
	}
}

In the example, Danny and Maria hold the chopsticks in their hands as they grab each one, and when Danny grabs chopstick 1 and Maria grabs chopstick 2, they both wait for the other to give up the chopsticks and wait indefinitely for each other to do so, which occurs as a deadlock.

So, be careful with locks, and when it comes to synchronization, always consider whether the thread should be synchronized; adding synchronization makes it less efficient, and not adding synchronization may produce inconsistent data like in the above example. So, the smaller the synchronization area (i.e., the locked area), the better, while keeping the data secure.


Recommended>>
1、Background extraction algorithms interframe difference method background difference method ViBe algorithm ViBe algorithm
2、TCP request header
3、New Media Boot Camp Today meet a better you and make a difference in your future
4、Artificial intelligence will surpass Moores Law as a driver of tech innovation
5、GitBranch management strategy

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号