1. Multithreading
1. Multithreading implementation
There are two ways to achieve multithreading:
- Inherit the Thread class, override the Run method, define the object, call the Start method
- The Create class implements the Runnable interface, which is passed as an argument to the thread's construction method. Define the object and call the Start method.
1.1. Inherit Thread
- Inheriting classes, overriding methods
classTDemo1extendsThread { PublicString name;//take a name for easy identification PublicTDemo1 (String name) {//Construction Method This. Name =name; } @Override Public voidRun () {//overriding the Run methodShow (); } Public voidShow () {SYSTEM.OUT.PRINTLN (name+ ": Talk show Time"); }}View Code
- Create an object, call the Start method to start the thread
New TDemo1 ("Liang Hongda"new TDemo1 ("Li Chen Wei" new TDemo1 ("Wentao" new TDemo1 (" Td1.start (); Td2.start (); Td3.start (); Td4.start () ;
View Code
1.2. Implement Runnable
classTDemo2ImplementsRunnable { PublicString name;//Identify PublicTDemo2 (String name) {//Construction Method This. Name =name; } @Override Public voidRun () {//Implementation MethodShow (); } Private voidShow () {SYSTEM.OUT.PRINTLN (name+ "New Media broadcasting"); } } View Code
- Create object, Invoke method start
New Thread ( new TDemo2, New TDemo2 ("30 Seconds Car" new Thread ( new TDemo2 ("Auto onion ring"new Thread (new TDemo2 ("Uncle said car")); Td1.start (); Td2.start (); Td3.start (); Td4.start () ;
View Code
A
Java Multithreading (thread Class)