Java multithreading improves one: traditional Threading Technology & Traditional Timers Timer

Source: Internet
Author: User
Tags thread class

Before we have a certain understanding of the basic knowledge of multithreading, then we will be more in-depth study of multithreading, but before learning we still have to review the traditional technology, this chapter we review is: traditional threading technology and traditional timer implementation.

One, traditional threading technology

1. How to create

1. Inherit the thread class

New Thread () {    @Override    publicvoid  run () {    }};t.start ();

2. Implement Runnable interface

New Thread (new  Runnable () {    @Override    publicvoid  run () {          while (true) {        }}}    ); T1.start ();

3. Implement callable Interface

Executorservice Pool == pool.submit (new  callable () {    publicthrows Exception {        returnnull;    }});

2. Compare

1. Thread VS Runnable

    • Java does not support multiple inheritance, allowing multiple interfaces to be implemented. Thread is a class, runnable is an interface
    • Runnable is suitable for sharing resources (multiple thread uses the same runnable)
    • public class Thread extends Object implements Runnable. Thread is a subclass of the Runnable interface

2, Runnable VS callable

    • The call () method of the callable can return a future type result and throw an exception, while the runnable run () method does not have these features
    • Callable usually uses Executorservice's Submit method to start the call method, Runnable can also start the Run method through the thread's Run method

Second, the traditional timers timer

1. Create

Point execution, parameter (timertask task, Date time), or (timertask task, long delay) delay after execution

New Timer (). Schedule (new  timertask () {    @Override    publicvoid  run () {     New Date ());

How long the delay executes, then timed execution, parameters (timertask task, long delay, long period) or (timertask task, Date Firsttime, long period) to the point of execution, and then timed execution

New Timer (). Schedule (new  timertask () {    @Override    publicvoid run () {    1000, 5000})

There are similar scheduleAtFixedRate(TimerTask task, long delay, long period) andscheduleAtFixedRate(TimerTask task, Date firstTime,long period)

2, schedule and scheduleatfixedrate differences

    • 2 parameter schedule: Executes immediately if the current time exceeds the first execution time, otherwise to the timing time
    • Schedule of 3 parameters: executes immediately if the current time exceeds the first execution time, otherwise to the scheduled time. The next task execution must be performed after the last task has finished executing. The next task execution time needs to see how long a task executes excetime and cycle time period, if Excetime>period executes immediately, otherwise waits period time to execute again.
    • Scheduleatfixedrate: The time to execute each task should be set. If there is too much processing time in the middle to cause the subsequent failure to execute as scheduled, the subsequent job is executed immediately until the timing of a task is caught. If the current time exceeds the first execution time, all subsequent jobs will be executed immediately until the timing of a task is caught. Because the fixed-rate may result in repeated execution at the same time, the actuator in the TimerTask needs to consider synchronization (not very well understood)
Schedule Example:
NewTimer (). Schedule (NewTimerTask () { Public voidrun () {Try{System.out.println (The Execute task! "+ Dateformatter.format ( This. Scheduledexecutiontime ())); Random Random=NewRandom (); intSlptime = Random.nextint (3) *1000 + 4000; System.out.println ("Exec time:" +slptime);        Thread.Sleep (Slptime); } Catch(interruptedexception e) {e.printstacktrace (); }}},startdate,5 * 1000);

Output Result:

Execute task! 2017-12-14 23:26:22//The current time exceeds the set first execution time and executes immediatelyEXEC time:1000//The first execution time is 1s less than the cycle time 2sExecute task! 2017-12-14 23:26:24//so the second time is executed after the first execution of 2sEXEC time:2000//The third execution time is 2s just equal to the cycle time 2sExecute task! 2017-12-14 23:26:26//so the third time executes after the second execution time of 2sEXEC time:3000//The third execution time is 3s greater than the cycle time 2sExecute task! 2017-12-14 23:26:29//so the fourth time executes after the third execution time 3sEXEC time:1000//after that, it's similarExecute task! 2017-12-14 23:26:31Exec time:2000Execute Task! 2017-12-14 23:26:33Exec time:3000Execute Task! 2017-12-14 23:26:36Exec time:1000Execute Task! 2017-12-14 23:26:38

scheduleatfixedrate Example:

System.out.println ("Start time:" + Dateformatter.format (NewDate ()));NewTimer (). Scheduleatfixedrate (NewTimerTask () {inti = 0; intSlptimes[] =New int[] {2000,4000,100,100,100};  Public voidrun () {Try{System.out.println ("Execute task:" + i + "! "+ Dateformatter.format ( This. Scheduledexecutiontime ()) + "Now time:" + Dateformatter.format (NewDate ()))            ; intSlptime = slptimes[i++%Slptimes.length]; System.out.println ("Exec time:" +slptime);        Thread.Sleep (Slptime); } Catch(interruptedexception e) {e.printstacktrace (); }}},startdate,2 * 1000);

Output Result:

Start Time:2017-12-15 00:00:09//start execution time not up to timedExecute task:0! 2017-12-15 00:01:00 now time:2017-12-15 00:01:00//start execution regularlyEXEC time:2000//just perform 2sExecute task:1! 2017-12-15 00:01:02 now time:2017-12-15 00:01:02//so the second time it's doneEXEC time:4000//second execution of 2s, resulting in a third deferred execution (third time should be performed on 2017-12-15 00:01:04)Execute task:2! 2017-12-15 00:01:04 now time:2017-12-15 00:01:06//third time in 2017-12-15 00:01:06 executionEXEC time:100//Third Execution 100msExecute task:3! 2017-12-15 00:01:06 now time:2017-12-15 00:01:06//since the delay was caused by the need to catch up, so immediately executed, the following similarEXEC time:100Execute Task:4! 2017-12-15 00:01:08 now time:2017-12-15 00:01:08Exec time:100Execute Task:5! 2017-12-15 00:01:10 now time:2017-12-15 00:01:10Exec time:2000Execute Task:6! 2017-12-15 00:01:12 now time:2017-12-15 00:01:12

3, the timer defect

The replacement of the timer Scheduledexecutorservice, this is not introduced in this article, the following will be elaborated Scheduledexecutorservice.

Resources:

"Multithreaded Video" Zhang Xiaoxiang

Java multithreading improves one: traditional Threading Technology & Traditional Timers Timer

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.