Dark Horse Programmer--multi-threaded synchronization of a layer of objects/two-layer objects/three-layer object comparison

Source: Internet
Author: User
Tags ticket

------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! -------

Objective:

In object-oriented thinking, the threading method can be divided into three types according to the level of the object to be created:

1, a layer of object writing: the use of extends thread, the replication of the parent class of the run () method, directly establish a thread instance object, this method is simple, suitable for single-task one-way requirements. Do not have much discussion here;

2, two-level object writing: Using the implements Runnable interface, the copy interface of the Run () method to get two levels of objects-often called task objects, and then by passing the two-level object into the (responsible for the main () method) of the first class object of the new Thread () construction parameters, The first-level object takes the polymorphic thread reference to the run () method;

Import java.util.random;//Two threads example of buying a ticket: Class FinalDemo1 implements Runnable {private int[] arr = new Int[6];p rivate int n=0 ;//private int num = 50;public void run () {for (int i = 0; i <, i++) {synchronized (this) {if (/*num > 0 && ; */n<6) {try {Thread.Sleep]} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "sold the first"//+ num--+ "Ticket! arr[n]= new Random (). Nextint (), n++;for (int a:arr) {System.out.print (a);}                    System.out.println ();}}}} public class MyThreadDemo2 {public static void main (string[] args) {FinalDemo1 f = new FinalDemo1 (); New Thread (F, "A"). STA RT (); New Thread (F, "B"). Start (); new Thread (F, "C"). Start ();}}

Two-layer notation Note: Shared resources are generally written on private properties, so when you create a thread, you cannot new multiple runnable! Otherwise, multithreading performs many of the same tasks; You should first new a Runnable object R and always pass this object to multiple new Thread (R).


3, three layers of object writing: On the basis of the two-layer notation, because of the complexity of the task, the establishment of a third object-often called the resource resource object to be responsible for the establishment of different processing methods, common is a production method, a consumer method, or to alternate execution of two other methods;

Because resources are unique, there are attributes to be shared, so more rigorous can be written as Singleton, so that the new thread (new Runnable (RES)) forms a three-tier object to complete a thread definition, and multiple threads of multiple tasks work together with a res to ensure security, Just synchronize the methods in Res.

Give two examples:

An example of a task, multiple threads: Although you can use the two-level object notation, but after extracting the third layer of resource objects, you can better control the thread task, such as alternating execution;

Two threads populate an array problem: Import Java.util.random;public class Test {/* * declares a shared array, two threads, two threads separated for a period of time (can write a random number),         * Add data to the array, and each thread will add 3 data to the group. * */public static void main (string[] args) {final Sharearr Sharearr = Sha                                Rearr.getinstance ();                                New Thread (New Runnable () {public void run () { for (int i = 0;i<3;i++) {Sharea                                Rr.addnumfirst ();                                }}). Start ();                Because a level three design is used, the same object is called on the resource, so different methods still share the private property, so the "i+1" elements of the two threads can be synchronized;                                New Thread (New Runnable () {public void run () {     for (int i = 0;i<3;i++) {                                   Sharearr.addnumsecond ();        }}). Start ();        }}class Sharearr {Private Sharearr () {};        private static Sharearr arr = null; public static Sharearr getinstance () {if (arr = = null) {synch                                Ronized (Sharearr.class) {if (arr = = null)                                {arr = new Sharearr ();        }}} return arr;        } private int[] array = new INT[6];        private int i = 0;        Boolean flag = true;                                Public synchronized void Addnumfirst () {while (!flag) {try {                        This.wait (); } catch (InterruptedexceptiOn e) {e.printstacktrace ();                }} try {thread.sleep (1000);                } catch (Interruptedexception e) {e.printstacktrace ();                } int num = new Random (). Nextint ();                System.out.println (Thread.CurrentThread (). GetName () + "Assign value to array" + (i+1) + "element" +num);                array[i++] = num;                Flag = false;        This.notify ();                        } public synchronized void Addnumsecond () {while (flag) {                        try {this.wait ();                        } catch (Interruptedexception e) {e.printstacktrace ();                }} try {thread.sleep (1000); } catch (Interruptedexception e) {e.printstAcktrace ();                } int num = new Random (). Nextint ();                System.out.println (Thread.CurrentThread (). GetName () + "Assign value to array" + (i+1) + "element" +num);                array[i++] = num;                Flag = true;        This.notify (); }}


Multi-tasking, multi-threaded example: generally have to use three-layer object writing;

Example of synchronized and lock mode for production & consumption: Producerconsumerdemoclass producerconsumerdemo2{public static void Main (string[] args) {Resource r=new Resource (); Producer pro=new Producer (R); Consumer con=new Consumer (R); Thread T1=new thread (PRO); Thread T2=new thread (PRO); Thread t3=new thread (con); Thread t4=new thread (con); T1.start (); T2.start (); T3.start (); T4.start (); System.out.println ("Hello world!");}} Class Resource {private string name;private int count=1;private boolean flag=false;public synchronized void set (String nam e) {while (flag) try{wait ();} catch (Exception e) {}this.name=name+ "--" +count++; System.out.println (Thread.CurrentThread (). GetName () + "... Producer ... "+this.name); Flag=true;this.notifyall ();} Public synchronized void out () {while (!flag) try{wait ();} catch (Exception e) {}system.out.println (Thread.CurrentThread (). GetName () + "... Consumer ... "+this.name); Flag=false;this.notifyall ();}} Class Producer implements Runnable{private Resource Res; Producer (Resource res) {this.res=res;} public void Run () {while (true) {Res.set ("+ goods +");}}} Class Consumer implements Runnable{private Resource Res; Consumer (Resource res) {this.res=res;} public void Run () {while (true) {Res.out ()}}} Import Java.util.concurrent.locks.*;class producerconsumerdemo2{public static void Main (string[] args) {Resource r=new Resource (); Producer pro=new Producer (R); Consumer con=new Consumer (R); Thread T1=new thread (PRO); Thread T2=new thread (PRO); Thread t3=new thread (con); Thread t4=new thread (con); T1.start (); T2.start (); T3.start (); T4.start (); System.out.println ("Hello world!");}} Class Resource {private String name;private int count=1;private boolean flag=false;private Lock lock=new reentrantlock (); Interface class private Condition condition_pro=lock.newcondition ();p rivate Condition condition_con=lock.newcondition (); public void Set (String name) throws interruptedexception//Interrupt exception {lock.lock (); Try{while (flag) condition_pro.await ();// Condition wait method, stop pro thread. this.name=name+ "--" +count++; System.out.println (Thread.CurrentThread (). GetName () + "... Producer ... "+thIs.name); flag=true;condition_con.signal ();} Finally{lock.unlock ();}} public void Out () throws Interruptedexception{lock.lock (); Try{while (!flag) condition_con.await ();//try{wait ();} catch (Exception e) {}system.out.println (Thread.CurrentThread (). GetName () + "... Consumer ... "+this.name); flag=false;condition_pro.signal ();//this.notifyall (); wake-up All}finally{lock.unlock ();}}} Class Producer implements Runnable{private Resource Res; Producer (Resource res) {this.res=res;} public void Run () {while (true) {Try{res.set ("+ goods +");} catch (Interruptedexception e) {}}}}class Consumer implements runnable{private Resource Res; Consumer (Resource res) {this.res=res;} public void Run () {while (true) {try{res.out ();} catch (Interruptedexception e) {}}}}


Dark Horse Programmer--multi-threaded synchronization of a layer of objects/two-layer objects/three-layer object comparison

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.