Java Multi-Threading and concurrency Library advanced applications

Source: Internet
Author: User
Tags thread class

1. Review of traditional threading mechanisms

1.1 Two traditional ways to create threads

Writing run code in the Run method covered by the thread subclass

//1. Using subclasses, put the code in run () of the subclassThread thread =NewThread () {@Override Public voidrun () { while(true) {                    Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace ();                } System.out.println (Thread.CurrentThread (). GetName ());        }            }        }; Thread.Start ();

> involves a previous point of knowledge: can you throw an exception on the Run method declaration to omit the try...catch processing of the Thread.Sleep () statement inside the Run method interrunptedexception?

Overwrite the Ancestor class method or implement the interface method (overwrite the Run method, and the source run method does not make a throw declaration), so you cannot make the throw declaration

Write code in the Run method of the Runnable object passed to the thread object

  

  

 Public Thread (Runnable target) {        init (null, Target, "thread-" + nextthreadnum (), 0);    }

Copy the target of the thread object in the Init method

Thread's Run method

/*** If This thread is constructed using a separate * <code>Runnable</code> run object, then that     * <code>Runnable</code> object ' s <code>run</code> method is called;     * Otherwise, this method does nothing and returns.     * <p> * Subclasses of <code>Thread</code> should override this method. *     * @see#start () *@see#stop () *@see#Thread (Threadgroup, Runnable, String)*/@Override Public voidrun () {if(Target! =NULL) {target.run (); }    }

//2. The code is placed in the Runnable object, and Runnable is the host of the Code runThread thread2 =NewThread (NewRunnable () {@Override Public voidrun () { while(true) {                    Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace ();                } System.out.println (Thread.CurrentThread (). GetName ());        }            }        }); Thread2.start ();

> Problem: If the Run method covered by the thread subclass always writes the running code and also passes a Runnable object for the thread subclass object, which run method does the thread execute?
   The run () of the subclass overrides the run () of the parent class, and if you do not overwrite the run () of the parent class, you will find runnable 

//3. Using the Run method in a subclass        NewThread (NewRunnable () {@Override Public voidrun () { while(true){                    Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Runnable:" +Thread.CurrentThread (). GetName ()); }            }        }){             Public voidrun () { while(true){                    Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Thread:" +Thread.CurrentThread (). GetName ());        }            }; }.start ();

  

 > involves a previous point of knowledge: How to construct an anonymous inner class object How do I call a non-default constructor method of a parent class?

> Multithreading mechanism will improve the efficiency of the program?

Less performance on a single CPU, but lower efficiency

the difference between sleep and wait in Java

① These two methods come from different classes, namely, sleep comes from the thread class, and wait comes from the object class.

Sleep is the static class method of thread, who calls who goes to sleep, even if you call B's Sleep method in a thread, actually a goes to sleep, to let the B thread sleep to call sleep in B's code.

② Lock: The most important thing is that the sleep method does not release the lock, and the wait method frees the lock so that other threads can use the synchronization control block or method.

Sleep does not sell system resources; Wait is the thread waiting for the pool to wait, to assign system resources, and other threads to consume the CPU. The general wait does not add a time limit, because if the wait thread runs out of resources, it is useless to wait for all threads in the Notify/notifyall wake-up waiting pool to be called by other threads before it enters the ready queue to wait for the OS to allocate system resources. Sleep (milliseconds) can be specified by time to wake it up automatically, if the time is less than the interrupt () force interrupt.

the role of Thread.Sleep (0) is "triggering the operating system to immediately re-compete with the CPU".

③ Use range: Wait,notify and notifyall can only be used in synchronous control methods or synchronization control blocks, and sleep can be used anywhere.

synchronized (x) {
x.notify ()
//or wait ()
}

2. Traditional timer Technology Review (jdk1.5 ago)

 Public classTraditionaltimertest {Static intCount = 0;  Public Static voidMain (string[] args) {//Execution starts in 10 seconds and executes every 3 seconds        NewTimer (). Schedule (NewTimerTask () {@Override Public voidrun () {System.out.println ("Bombing ..."); }        }, 10000,3000); /*** Required: 2 seconds, 4 seconds interval to perform scheduled tasks*/        classMytimertaskextendstimertask{@Override Public voidRun () {count= (count+1)%2; System.out.println ("Bombing ..."); NewTimer (). Schedule (NewMytimertask (), 2000 + 2000*count); }        }        NewTimer (). Schedule (NewMytimertask (), 2000);  while(true){            Try{System.out.println (NewDate (). getseconds ()); Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }                //Quartz Monday ~ Friday Execution of tasks, week 6th not executed    }}

Java multi-threading and concurrency Library advanced applications

Related Article

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.