West Side dreams Old man 2017-03-28 18:00
When we design threads, sometimes we want him to share the data, and sometimes hopefully not, so what do we do with these two situations?
Do not share data
Do not share data is each is a separate thread, and then to adjust their own start method can not share the data, the following look at the code.
public class Notsharedata extends Thread {
private int count=5;
Public Notsharedata (String name) {
Super ();
This.setname (name);
}
@Override
public void Run () {
Super.run ();
while (count>0) {
count--;
System.out.println (Thread.CurrentThread (). GetName () + "calculated count=" +count);
}
}
}
Next look at the test method.
Notsharedata nsd1=new Notsharedata ("1");
Notsharedata nsd2=new Notsharedata ("2");
Notsharedata nsd3=new Notsharedata ("3");
Nsd1.start ();
Nsd2.start ();
Nsd3.start ();
Three threads are instantiated here, and by invoking the Start method of each thread, you can not share the data, and see the results below.
Do not share data results
Sharing data
Sharing data is where multiple threads can access the same object.
public class Sharedata extends Thread {
private int count=5;
@Override
public void Run () {
Super.run ();
count--;
System.out.println (Thread.CurrentThread (). GetName () + "calculated count=" +count);
}
}
There is no need to use a while loop, because we are going to have multiple threads to access together.
Here's a look at the test method.
Sharedata sd=new sharedata ();
Thread t1=new Thread (SD, "1");
Thread t2=new Thread (SD, "2");
Thread t3=new Thread (SD, "3");
Thread t4=new Thread (SD, "4");
Thread t5=new Thread (SD, "5");
T1.start ();
T2.start ();
T3.start ();
T4.start ();
T5.start ();
The thread method constructor is called here
The constructor that is called
So here are five threads that are calling the same object and sharing the data. Let's see the results.
Results of shared data
Here you can see that a problem with shared data, thread safety issues. In fact, in the JVM, the i--operation is divided into three parts, 1. Take the original I value 2. Calculate I-1 3. To assign a value to I, then multiple threads are accessing this operation, there will be a thread-safe problem, so add the Synchronized keyword before the Run method.
By adding the Synchronized keyword before the Run method, multiple threads are processed in a queued manner when the Run method is executed. When a thread calls run, it is determined whether the Run method is locked, if it is locked, that other threads are calling the Run method, and must wait for the other thread to finish calling the Run method before the Run method can be executed.
Synchronized can be locked on any object and method, and the lock code is called a "mutex" or "critical section".
Today to enjoy the attention of a wave ~ ~ Thank you for watching.