There are two ways to implement multithreading in Java: Inheriting the thread class and implementing the Runnable method, overriding the Run method, and then invoking the start () method to start the thread. Using runnable is much better than thread, mainly for the following three reasons: (1) The Java language is single-inheritance, and if you inherit the thread class, you cannot inherit other classes. (2) A situation where the same resource is handled by a thread area that is suitable for multiple identical program codes. Test (thread Class)
Packagecom.csdhsm.concurrent;/*** @Title: Threaddemo.java * @Package: com.csdhsm.concurrent * @Description inherit thread test *@authorHan * @date 2016-4-18 pm 3:45:30 *@versionV1.0*/ Public classThreaddemoextendsThread {Private intTicket = 3; Private intID; PublicThreaddemo (intID) { This. ID =ID; } @Override Public voidrun () { while(Ticket > 0) {System.out.println ( This. ID + "--" + ticket--); } } Public Static voidMain (string[] args) {NewThreaddemo (1). Start (); NewThreaddemo (2). Start (); NewThreaddemo (3). Start (); }}
Results
Test (Runnable Class)
Packagecom.csdhsm.concurrent;/*** @Title: Runnabledemo.java * @Package: Com.csdhsm.concurrent * @Description Implement Runnale interface *@authorHan * @date 2016-4-18 pm 3:47:40 *@versionV1.0*/ Public classRunnabledemoImplementsrunnable{Private intTicket = 5; Private intID; PublicRunnabledemo (intID) { This. ID =ID; } @Override Public voidrun () { while(Ticket > 0) {System.out.println ( This. ID + "--" + ticket--); } } Public Static voidMain (string[] args) {Runnabledemo demo=NewRunnabledemo (1); NewThread (Demo). Start (); NewThread (Demo). Start (); NewThread (Demo). Start (); }}
Results
Summary 1. In the vast majority of concurrent programming, the method of inheriting the Runnable interface is used. 2. In the example above, when using the thread class, you must instantiate the object every time, so each thread has its own resources. And in the second method, we also new 3 thread objects, but only one Runnable object, 3 thread objects share the code in this Runnable object, so there will be 3 threads together to complete the results of the ticket selling task.
Java Concurrent Programming (i) two ways to implement multithreading (Thread,runnable)