Multithreading synchronization Mutex instances-Multiple threads sharing data

Source: Internet
Author: User
Tags mutex
• Case Problems

Design 4 threads, where two threads add 1 to J each time, and two threads reduce each J by 1 each time, write the program. This is a Java thread interview face test, the problem on the internet there are many answers. So, how did the answer come? Simple to analyze and summarize. • Train of Thought

By the title, we need to create 4 threads to implement two methods, one for the variable plus 1, and one for the same variable of 1. In this, all the methods must be guaranteed to synchronize the variables. So, we can use two runnable, but to manipulate the same variable, there must be an operable external variable, and the operation is mutually exclusive, that is, neither process can manipulate the data at the same time. • To achieve the first step

Let's take two threads as an example to reduce the data by 1. Then we define a class, put it in a shared external variable, class implement Runnable, execute Subtract method, two threads share the same Runnable object, then realize data sharing. The code is as follows:

public class Multithreadsharedata {public

static void Main (string[] args) {
	ShareData1 data1 = new ShareData1 (); C5/>new Thread (New MyRunnable1 (DATA1)). Start ();
	New Thread (New MyRunnable2 (DATA1)). Start ();

Class ShareData1 implements runnable{
private int j=100;
@Override public
Void Run () {while
	(true) {
		j--
}}}

• Perfect the second step

In the first step, we did not meet the requirements of our topic, we asked for a reduction, so we should have two runnable objects. Two Runnable objects also manipulate the same external variable, so you have to have an operable external object. The code is as follows

public class Multithreadsharedata {private static ShareData1 data1=new ();
		public static void Main (string[] args) {ShareData1 data1 = new ShareData1 ();
		New Thread (New MyRunnable1 (DATA1)). Start ();
		
		
	New Thread (New MyRunnable2 (DATA1)). Start ();
	} class MyRunnable1 implements runnable{private ShareData1 data1;
	Public MyRunnable1 (ShareData1 data1) {this.data1 = data1;
	@Override public void Run () {data1.decrement ();
	} class MyRunnable2 implements runnable{private ShareData1 data1;
	Public MyRunnable2 (ShareData1 data1) {this.data1 = data1;
	@Override public void Run () {data1.increment ();
	} class sharedata1{private int j=0;
	public synchronized void Increment () {j + +;
	Public synchronized void Decrement () {j--; }

	
}

• Add We can still run over there. Object as the internal class of a class, shared data as the member variables in this external class, each thread of the operation of the shared data is also assigned to the external class, to achieve data on the shared data awakened brother operation of mutual exclusion and communication. The code is as follows:

public class Multithreadsharedata {private static ShareData1 data1=new ShareData1 (), public static void Main (string[] Ar
	GS) {ShareData1 data2 = new ShareData1 ();
	New Thread (New MyRunnable1 (DATA2)). Start ();
	
	New Thread (New MyRunnable2 (DATA2)). Start ();
	Final ShareData1 data1 = new ShareData1 ();
			
		New Thread (New Runnable () {@Override public void run () {data1.decrement ();
	}). Start ();
		New Thread (New Runnable () {@Override public void run () {data1.increment ();
}). Start (); Class MyRunnable1 implements runnable{private ShareData1 data1; public MyRunnable1 (ShareData1 data1) {This.data
1 = data1;

@Override public void Run () {data1.decrement ();} Class MyRunnable2 implements runnable{private ShareData1 data1; public MyRunnable2 (ShareData1 data1) {this.data1 =
Data1;

@Override public void Run () {data1.increment ();}

Class ShareData1 implements runnable{private int j=0; public synchronized void Increment () {j + +;} Public synchronized void Decrement () {j--;} }

• Last

According to this idea, we give our final answer, the code is as follows

Package cn.itcast.heima2;
		public class Multithreadsharedata {public static void main (string[] args) {Factory Factory = new Factory ();
		T1 T1 = new T1 (factory);
		T2 t2 = new T2 (factory);
		Thread thread1 = new Thread (t1, "Add thread 1");
		Thread thread2 = new Thread (t1, "Add thread 2");
		Thread thread3 = new Thread (t2, "Subtract thread 1");
		Thread thread4 = new Thread (t2, "Subtract thread 2");
		Thread1.start ();
		Thread2.start ();
		Thread3.start ();
	Thread4.start ();

	} class T1 implements Runnable {Factory Factory = null;
	T1 (Factory Factory) {this.factory = Factory;
			@Override public void Run () {while (true) {Factory.add ();
			try {thread.sleep (int) math.random () * 10);
			catch (Interruptedexception e) {e.printstacktrace ();

	Class T2 implements Runnable {Factory Factory = null;
	T2 (Factory Factory) {this.factory = Factory;
			@Override public void Run () {while (true) {factory.min ();
			try {thread.sleep (int) math.random () * 10); catch (inTerruptedexception e) {e.printstacktrace ();

	'}} ' class Factory {int J;
	Factory () {j = 0;
		} synchronized void Add () {j + +;
	System.out.println (Thread.CurrentThread (). GetName () + ":" +j);
		} synchronized void min () {j--;
	System.out.println (Thread.CurrentThread (). GetName () + ":" +j); }
}

• Summary • Multithreading access to shared objects and data 0 if each thread executes the same code, you can use the same Runnable object, which has the shared data in the Runnable object, for example, the ticket system can do so.
0 if each thread executes different code, it is necessary to use a different runnable object, like the next two ways to implement the data sharing between these runnable objects:
Let's say that the shared data is encapsulated in another object, and then the beloved one is passed on to each Runnable object, and each thread's manipulation of the shared data is also assigned to the object, which makes it easy to implement the mutex and communication of the Brother's operations against the data.
§ These runnable objects as internal classes in a class, shared data as member variables in this external class, and each thread's method of manipulating shared data is also assigned to external classes to enable mutual exclusion and communication of operations that are awakened by shared data. These methods that invoke the outer class as individual runnable objects of the inner class
§ The combination of the above two ways: encapsulate the shared data in another object, and each thread's method of manipulating the shared data is assigned to that object as a member variable in the outer class or as a local variable in the method. The Runnable object for each thread acts as the inner class or local inner class of the member inside the outer class.
For the purpose of synchronization, several pieces of code to synchronize mutexes are best placed in separate methods, which are placed in the same class, which makes it easier to synchronize mutual exclusion and communication between them.

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.