A __java of Java synchronized's review

Source: Internet
Author: User
Tags ticket
0: As long as it involves simultaneous execution, it will be multithreaded, for example, four Windows selling tickets at the same time
1: There are two ways to implement multithreading, one of which is extends Thread, and the second is implement Runnable
If the explanation is:
In the first way, thread tasks and threads are bound together, creating four threads creates 4 of resources
In the second way, the thread task and the thread object are separated, and only one task object (one resource) is created, and four threads are allowed to execute each.

The first method is as follows: Each window has 50 ticket
class Ticket1 extends thread{
    int num=50;
    public void Run () {while
        (true) {
            if (num>0)
                System.out.println (Thread.CurrentThread (). GetName () + " Sale "+num--);


}}} Ticket T1 = new Ticket ();
Ticket t2 = new Ticket ();
T1.start ();
T2.start ();


The second method is as follows: Several windows are altogether 50 tickets
class Ticket implements runnable{
    int num=50;
    public void Run () {while
        (true) {
            if (num>0)
                System.out.println (Thread.CurrentThread (). GetName () + "Sale" +num--);

}} Note that there is only one Ticket object, and then the thread is created with this Ticket, no matter how many windows

Ticket Ticket = new Ticket ();
thread T1 = new thread (ticket);
Thread t2 = new Thread (ticket);
T1.start ();
T2.start ();


2: If there is only one sentence in the execution, then there is no synchronization problem,

To simulate the synchronization problem, we are in the
if (num>0)
                System.out.println (Thread.CurrentThread (). GetName () + "Sale" +num--);
Continue execution below:
if (num>0) {
				System.out.print ("  **********" +num);
				System.out.print ("" +num);
				System.out.print ("" +num);
				System.out.print ("" +num);
				System.out.print ("" +num);
				System.out.print ("" +num);
				System.out.print ("" +num);
				System.out.print ("" +num);
				System.out.println ("" "+num);
				}

This will be found, but one is carried on to the general time, for example, in the input, the CPU was robbed by other processes, and then came back to perform


In order to solve this kind of synchronization problem, introduce synchronized, synchronization,
Synchronized method inside of things, to perform must be all done, and database transactions a bit like, or a bit to the toilet, this person is over, others can, the total can not be on the other half of it, you beat to the. Synchronized can be used to modify the method, the lock is actually this, if it is a static method, then the lock is class

So now it's just a matter of using this synchronized (obj) to just output something,

Class Ticket implements runnable{
    int num=50;
	Object obj = new Object ();
    public void Run () {while
        (true) {
			synchronized (obj) {
				if (num>0)
					System.out.print ( Thread.CurrentThread (). GetName () + "Sale" +num--+ "$$$$$$$$$$$");
				if (num>0) {
				System.out.print ("  **********" +num);
				System.out.print ("" +num);
				System.out.print ("" +num);
				System.out.print ("" +num);
				System.out.print ("" +num);
				System.out.print ("" +num);
				System.out.print ("" +num);
				System.out.print ("" +num);
				System.out.println ("" +num);}}}}


An example: A bank can save money, two people save at the same time, each save 3 times, each save 100
public class savemoney{public
	static void Main (string[] args) {person person
		= new person ();
		thread T1 = new thread (person);
		Thread t2 = new Thread (person);
		thread t3 = new thread (person);
		
		T1.start ();
		T2.start ();
		T3.start ();
	}


Class Person implements runnable{
	
	Bank = new Bank ();
	int times = 3;
	public void Run () {
		//save 1001 times, altogether 3 for
		(int i=0;i<3;i++)
		bank.add;
	}


class bank{
		int sum = 12345;
		Public synchronized void Add (int addednumber) {
			
			System.out.print (Thread.CurrentThread (). GetName () + "The balance before deposit is" + sum);
			sum = Sum+addednumber;
			System.out.println ("  current balance is" +sum);
		}




The 3:synchronized modified function is the synchronization function, and what is the synchronization lock for the synchronization function. Is this,
But if it is a static synchronization function, then the synchronization lock is the class

Class Ticket implements runnable{static int num = 50;
	Boolean flag = true;
					public void Run () {if (flag==true) {while (true) {synchronized (ticket.class) {try{thread.sleep (20); }catch (Exception e) {//} if (num>0) {System.out.print (Thread.CurrentThread (). GetName () + "Sale
					"+num--);
						} if (num>0) {System.out.print ("**********" +num);
						System.out.print ("" +num);
						System.out.print ("" +num);
						System.out.print ("" +num);
						System.out.print ("" +num);
						System.out.print ("" +num);
						System.out.print ("" +num);
						System.out.print ("" +num);
					System.out.println ("" +num);
			}}else{while (true) {fun ();
					}} public synchronized static void Fun () {try{thread.sleep (20); }catch (Exception e) {//} if (num>0) {System.out.print (Thread.CurrentThread (). GetName () + "Sale" +n
					um--); } if (num>0) {System.out.print ("-----------------------------------------"+num);
						System.out.print ("" +num);
						System.out.print ("" +num);
						System.out.print ("" +num);
						System.out.print ("" +num);
						System.out.print ("" +num);
						System.out.print ("" +num);
						System.out.print ("" +num);
					System.out.println ("" +num);
		}} public class saleticket{public static void Main (string[] args) {Ticket t = new Ticket ();
		thread T1 = new Thread (t);
		Thread t2 = new Thread (t);
		T1.start (); Try{thread.sleep (20);}
		catch (Exception e) {} t.flag=false;
	T2.start (); }
}


4: Occurrence of the deadlock:

/** simulate the deadlock situation, a to go upstairs, b to go downstairs, a on the 1 floor, B on the 4 floor, 2 and 3 floors have lock a upstairs order is to 2 floor, then 3 floor, B downstairs is first 3 floor, then 2 floor. The smooth situation is a took the 2 floor key, and then took the third floor of the key, then B began to go downstairs which 3 floor of the key, then the 2 floor of the key so there will be two people, A has a 2 floor key, but to 3 floor key, B has 3 floor key, but to 2 floor of the key * * public class
		deadlock{public static void Main (string[] args) {test test = new test ();
		thread T1 = new thread (test);
		Thread t2 = new Thread (test);
		Test.flag = 0;
		T1.start (); Let the main thread sleep for a while, then execute the Start method above, otherwise the Try{thread.sleep (500) is not executed;
		catch (Exception e) {} test.flag=1;
		
	T2.start ();
	Class Test implements runnable{int flag;
	Object lock1 = new Object ();
	Object Lock2 = new Object ();
					public void Run () {if (flag==0) {while (true) {synchronized (lock1) {try{thread.sleep (50);
					}catch (Exception e) {//} System.out.println ("Flag = 1 already have lock1, now to Lock2");
					Synchronized (Lock2) {System.out.println ("Flag = 1 acquired Lock2");
					}}else{while (true) {synchronized (Lock2) {try{thread.sleep (50); }catch (Exceptione) {//} System.out.println ("Flag = 2 already has Lock2, now to Lock1");
					Synchronized (LOCK1) {System.out.println ("Flag = 1 acquired lock1");
 }
				}
			}
		}
	}
}


5: The concurrency security problem in the single case mode,
The Idle type has:
public class singletest{public
	static void Main (string[] args) {
		test test = new test ();
		thread T1 = new thread (test);
		Thread t2 = new Thread (test);
		thread t3 = new thread (test);
		thread T4 = new thread (test);
		
		T1.start ();
		T2.start ();
		T3.start ();
		T4.start ();
	}


Class Test implements runnable{public
	void  Run () {single single
		= Single.getinstance ();
		System.out.println ("" +single.tostring ());
	}
}


Class single{
	private static single;
	Private single () {} public
	synchronized static single getinstance () {
		if (single==null) {
			single= new Single ();
			return single;
		} else return single 
			;
	}
	









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.