Java Threads and timed tasks

Source: Internet
Author: User

The thread concept is not to be mentioned here.

Here are three ways to start a thread.

1. Inherit thread
 Public class extends Thread {    @Override    publicvoid  run () {        int i  = 0 ;          while (I <) {            i+ +;            System.out.println ("This is thread thread");     }}}

Call

New threadtest (); Threadtest.start ();
2. Implement the Runnable interface
 Public classRunnabletestImplementsrunnable{intA; intb;  PublicRunnabletest (intAintb) {         This. A =A;  This. B =b; }     Public voidrun () {inti = 0;  while(I < 10) {i++; System.out.println ("A:" + A + "B:" +C); }    }}

Call

New Runnabletest (5,6); New Thread (Threadextends). Start ();
3. Anonymous class
New Thread () {          publicvoid  run () {              int i = 0;                while (I <) {                  i+ +;                  System.out.println ("This is Inside Thread");}}          ; T.start ()

Thread Common methods:

1. The sleep thread pauses and the sleep is executed again.

2. Join is added to the current thread, and if joined, the joined thread is executed before the current thread is executed.

3. SetPriority set thread priority.

4. Yield temporary suspension.

Here is a method for performing tasks on a timed basis, using the TimerTask
 Public Static void Main (String args[]) {        New Timer ();         New TimerTask () {            int i = 0;            @Override            publicvoid  run () {                System.out.println (i);                I++                ; if (i = = 5)                    t.cancel ();            }        };        T.scheduleatfixedrate (TimerTask,0,1500);

Java threads and Scheduled tasks

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.