Creating Threads and Synchronized keywords

Source: Internet
Author: User
Tags thread class ticket

A long time did not update the blog, just this time to work on the use of threads, it took a little time to review (learning) a bit of knowledge of threading. In this article I will explain the threads around the following points:

1. Creation of threads (thread,runnable)

2.Synchronized Keywords (producer consumers)

One, thread creation

I believe that the students who have studied Java know that creating a thread is nothing but two ways:

(1) inherit the thread class;

(2) Realize runnable interface;

So what's the difference between these two ways? There is still a difference in the way of implementation, inheriting the thread class will need to rewrite the thread parent class of the Run method, the Run method is the execution of the common code block, and the implementation of runnable is the interface of the run method of the implementation, the two methods of the Run method of the same effect. Let's analyze the code together:

package Com.cct.thread;class MyThread extends thread{private int ticket =       10; public void Run () {for (int i =0;i<500;i++) {if (this.ticket>0) {System.out.pri              Ntln (Thread.CurrentThread (). GetName () + "Selling tickets---->" + (this.ticket--));   }}}} (1) test a public static void main (string[] args) {MyThread mt1 = new MyThread (); MyThread mt2 = new MyThread ();    MyThread mt3 = new MyThread (); Three objects were created Mt1.start (); Mt2.start (); Mt3.start ();} (2) test two public static void main (string[] args) {MyThread thr=new MyThread (); Thread A=new thread (THR, "number 1th"); Thread B=new thread (THR, "number 2nd");   Thread C=new thread (THR, "number 3rd"); An object is called with three threads A.start (); B.start (); C.start ();} 

Students should be able to see the difference between the two test methods above, the first main will give three threads to allocate 10 tickets for sale, and the second is a total of 10 tickets for sale, See a lot of people on the Internet to describe the difference between inheriting the thread and implementing the Runnable interface is to consume the same resources together, I think this statement is wrong, regardless of which way the implementation of the thread is achievable, this should be noted. The difference is that in addition to the way it is written on the class, I think the big difference is that Java only supports but inherits, but can be implemented more, so I believe that implementing runnable is more extensible than inheriting thread.

Second, synchronized key words

This is one of the most common keywords used by threads, and its purpose is that only one thread obtains the lock at the same point and enters the execution code, and the other line Cheng also needs to obtain the lock, and waits outside until the thread finishes executing.

First, when two concurrent threads access the same object in the synchronized (this) synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block.

Second, however, when a thread accesses one synchronized (this) of an object to synchronize a block of code, another thread can still access the non-synchronized (this) synchronous code block in the object.

Third, in particular, when a thread accesses one synchronized (this) of an object to synchronize a block of code, other threads will block access to all other synchronized (this) synchronization blocks in object.

The third example also applies to other synchronous blocks of code. That is, when a thread accesses a synchronized (this) of object to synchronize a block of code, it obtains the object lock of the objects. As a result, other threads are temporarily blocking access to all of the synchronization code portions of the object.

The above rules apply to other object locks as well.

Not much to say, first to code for example:

First, when two concurrent threads access the same object in the synchronized (this) synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block.

public class Thread1 implements Runnable {
public void Run () {
Synchronized (this) {
for (int i = 0; i < 5; i++) {
System.out.println (Thread.CurrentThread (). GetName () + "synchronized loop" + i);
}
}
}
public static void Main (string[] args) {
Thread1 T1 = new Thread1 ();
Thread ta = new Thread (T1, "A");
Thread TB = new Thread (T1, "B");
Ta.start ();
Tb.start ();
}
}

Result:   
     A synchronized Loop 0  
     A synchronized loop 1  
     a synchronized loop 2  
     A Synchronized loop 3  
     A synchronized Loop 4  &NBSP;
     B synchronized loop 0  
     B synchronized loop 1  
      b synchronized Loop 2  
     B synchronized Loop 3  
     B synchronized Loop 4

Second, however, when a thread accesses one synchronized (this) of an object to synchronize a block of code, another thread can still access the non-synchronized (this) synchronous code block in the object.

public class Thread2 {
public void M4t1 () {
Synchronized (this) {
int i = 5;
while (i--> 0) {
System.out.println (Thread.CurrentThread (). GetName () + ":" + i);
try {
Thread.Sleep (500);
} catch (Interruptedexception IE) {
}
}
}
}
public void M4t2 () {
int i = 5;
while (i--> 0) {
System.out.println (Thread.CurrentThread (). GetName () + ":" + i);
try {
Thread.Sleep (500);
} catch (Interruptedexception IE) {
}
}
}
public static void Main (string[] args) {
Final Thread2 myt2 = new Thread2 ();
thread T1 = new Thread (new Runnable () {public void run () {myt2.m4t1 (); }}, "T1");
Thread t2 = new Thread (new Runnable () {public void run () {myt2.m4t2 (); }}, "T2");
T1.start ();
T2.start ();
}
}

Results:
T1:4
T2:4
T1:3
T2:3
T1:2
T2:2
T1:1
T2:1
t1:0
t2:0

Third, in particular, when a thread accesses one synchronized (this) of an object to synchronize a block of code, other threads will block access to all other synchronized (this) synchronization blocks in object.

    //To Modify the Thread2.m4t2 () method:      Public voidm4t2 () {synchronized( This) {                 inti = 5;  while(i--> 0) {System.out.println (Thread.CurrentThread (). GetName ()+ " : " +i); Try{Thread.Sleep (500); } Catch(Interruptedexception IE) {}}} Result: T1:4T1:3T1:2T1:1T1:0T2:4T2:3T2:2T2:1T2:0

The third example also applies to other synchronous blocks of code. That is, when a thread accesses a synchronized (this) of object to synchronize a block of code, it obtains the object lock of the objects. As a result, other threads are temporarily blocking access to all of the synchronization code portions of the object.

  Modify the Thread2.m4t2 () method as follows: public     synchronized void M4t2 () {            int i = 5;            while (i--> 0) {                 System.out.println (Thread.CurrentThread (). GetName () + ":" + i);                 try {                      thread.sleep;                 } catch (Interruptedexception IE) {}}}       result:       t1:4       T1:3       t1:2       t1:1       t1:0       t2:4       t2:3       t2:2       t2:1       t2:0

The above rules apply to other object locks as well:

public class Thread3 {class Inner {private void m4t1 () {int i = 5;                     while (i--> 0) {System.out.println (Thread.CurrentThread (). GetName () + ": inner.m4t1 () =" + i);                     try {thread.sleep (500);                } catch (Interruptedexception IE) {}}} private void M4t2 () {                int i = 5;                     while (i--> 0) {System.out.println (Thread.CurrentThread (). GetName () + ": inner.m4t2 () =" + i);                     try {thread.sleep (500); } catch (Interruptedexception IE) {}}} private void M4t1 (Inner      Inner) {synchronized (inner) {//Use Object lock Inner.m4t1 ();      } private void M4t2 (Inner Inner) {inner.m4t2 (); } public static void Main (string[] args) {final Thread3 myt3 = new Thread3 ();           Final Inner Inner = Myt3.new Inner ();      thread T1 = new Thread (new Runnable () {public void run () {myt3.m4t1 (inner);}}, "T1");      Thread t2 = new Thread (new Runnable () {public void run () {myt3.m4t2 (inner);}}, "T2");      T1.start ();   T2.start (); } }

The key Synchronizedde lock is an object lock, rather than a piece of code (method) as a lock, which thread in the example code to execute the method with the Synchronized keyword, the thread is holding the object of the method of the lock, different objects get a different object lock, They do not affect each other, there is a situation is the same, that is, in the static method with the Synchronized keyword, which means locking class class, classes of locks, can be called Class lock, when used to pay attention to the distinction.

Synchronized part of the reference: http://www.wgblogs.com/here to express our thanks

Creating Threads and Synchronized keywords

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.