Re-learning Java Basics (iv): Creating and executing threads

Source: Internet
Author: User

1. Inherit thread

  

 Public class extends thread{    publicvoid  run () {        System.out.println () {Thread.CurrentThread (). GetName ());    }          Public Static void Main (string[] args) {        new  testthread ();        T.start ();    }}

2. Implement Runnable

 Public class Implements runnable{    @Override    publicvoid  run () {        System.out.println ( Thread.CurrentThread (). GetName ());            }      Public Static void Main (string[] args) {        new Thread (new  testrunnable ());        T.start ();    }}

3. Thread pool

 Public classTestthreadpool { Public StaticExecutorservice Singlepool =Executors.newsinglethreadexecutor (); Private StaticExecutorservice Fixedpool = Executors.newfixedthreadpool (2); Private StaticExecutorservice Cachedpool =Executors.newcachedthreadpool (); Private StaticThreadpoolexecutor TPE =NewThreadpoolexecutor (5, ten, Timeunit.seconds,NewLinkedblockingqueue<runnable> (),NewDefaultthreadfactory (),NewThreadpoolexecutor.abortpolicy ()); Private Static classDefaultthreadfactoryImplementsthreadfactory{@Override Publicthread Newthread (Runnable r) {thread T=NewThread (R); returnT; }    }         Public Static voidMain (string[] args) {Singlepool.execute (Newtestthreadp ()); Fixedpool.execute (Newtestthreadp ()); Cachedpool.execute (Newtestthreadp ()); Tpe.execute (Newtestthreadp ()); }        }classTestthreadpImplementsrunnable{@Override Public voidrun () {System.out.println (Thread.CurrentThread (). GetName ()); }    }

Re-learning Java Basics (iv): Creating and executing threads

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.