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