Java Sync Lock (synchronized)

Source: Internet
Author: User

The time slices in Java where the CPU is allocated to each thread are random and many threads in Java are shared by a single resource. For example, trains sell tickets, train tickets are certain, but the window selling train tickets are everywhere, each window is equivalent to a thread, so many threads share all the train ticket this resource. If two threads use the resource at one point in time, they will get the same train ticket (the same as the seat number), causing trouble to the passengers. For example, the following program:

Package com.pakage.ThreadAndRunnable;

public class Runnable_demo implements runnable{
	private int ticket=10;
	Public Runnable_demo () {		
	}
	@Override public
	void Run () {for
		(int i=0;i<20;i++) {
				if ( this.ticket>0) {
					//hibernate 1s seconds, in order to make the effect more obvious, it may not be effective
					try {
						thread.sleep (1000);
					} catch (Exception e) {
						e.printstacktrace ();
					}
					System.out.println (Thread.CurrentThread (). GetName () + "window sold:" +this.ticket--+ ticket ");
	
	 }} public static void Main (String args[]) {
		 Runnable_demo demo=new runnable_demo ();
		 Create three Windows
		 new Thread (demo, "a") based on train tickets. Start ();
		 New Thread (demo, "B"). Start ();
		 New Thread (demo, "C"). Start ();
	 }
	

Program Run Result:


We can see that window C and window B have sold 10th tickets, and A and b windows have sold No. 0 and-1th tickets respectively. The reason for this situation is 1, c thread and B thread in the ticket=10, C thread out of the 10th ticket, ticket has not come and reduce the 1,b thread to take out the ticket at this time ticket is equal to 10; 2, in Ticket=1, C thread took out 1th tickets, Ticket has not come and reduce 1,a, B thread has entered the IF Judgment statement, then ticket minus 1, then when a, B thread to pick up the ticket when the number No. 0 and-1th tickets.

How does this change, we can do this: when a thread to use the train ticket this resource, we give it a lock, and so it after the thing is done in the lock to another thread to use this resource. This will not happen. The ability to implement this lock requires the use of the synchronized keyword.

Synchronized this keyword has two uses 1, puts the method name to form the synchronization method before, 2, puts in the block to compose the synchronized block.

1, using the synchronization method to the above example should be:

Package com.pakage.ThreadAndRunnable;

public class Runnable_demo implements runnable{
	private int ticket=10;
	Public Runnable_demo () {		
	}
	@Override public
	void Run () {for
		(int i=0;i<20;i++) {
				if ( this.ticket>0) {
					//hibernate 1s seconds, in order to make the effect more obvious, it may not be effective
					try {
						thread.sleep (1000);
					} catch (Exception e) {
						e.printstacktrace ();
					}
					This.sale ();
	
	}} Public synchronized void Sale () {
		if (this.ticket>0) {
			System.out.println (Thread.CurrentThread (). GetName () + "window to sell:" +this.ticket--+ "ticket");
		}
	
	 public static void Main (String args[]) {
		 Runnable_demo demo=new runnable_demo ();
		 Create three Windows
		 new Thread (demo, "a") based on train tickets. Start ();
		 New Thread (demo, "B"). Start ();
		 New Thread (demo, "C"). Start ();
	 }
	

The output of the program is:

2, use the synchronized block to modify the above example:

Package com.pakage.ThreadAndRunnable;

public class Runnable_demo implements runnable{
	private int ticket=10;
	Public Runnable_demo () {		
	}
	@Override the public
	Void run () {for
		(int i=0;i<20;i++) {
			synchronized ( This) {
				if (this.ticket>0) {
					//hibernate 1s seconds, in order to make the effect more obvious, you may not be able to effect a
					try {
						thread.sleep (1000);
					} catch (Exception e) {
						e.printstacktrace ();
					}
					System.out.println (Thread.CurrentThread (). GetName () + "window sold:" +this.ticket--+ ticket ");
	
	 }}} public static void Main (String args[]) {
		 Runnable_demo demo=new runnable_demo ();
		 Create three Windows
		 new Thread (demo, "a") based on train tickets. Start ();
		 New Thread (demo, "B"). Start ();
		 New Thread (demo, "C"). Start ();
	 }
	

The output of the program:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.