Java implements multithreading in two ways:
1. inherit the Thread class and override the run method.
Package Com. bjdata. test; Public Class Threadtest Extends Thread {string name = "" ; Public Threadtest (string N) {name = N ;} Public Void Run (){ For ( Int I = 0; I <6; I ++ ) {System. Out. println (name + ": Hello:" + I );}} Public Static Void Main (string [] ARGs) {threadtest test1 = New Threadtest ("" ); Threadtest Test2 = New Threadtest ("B" ); Test1.start (); test2.start ();}}
Note:ProgramThe start method instead of the run method is called during running.
First running result:
A: Hello: 0B: Hello:0B: Hello:1B: Hello:2B: Hello:3B: Hello:4B: Hello:5A: Hello:1A: Hello:2A: Hello:3A: Hello:4A: Hello:5
The second running result:
B: Hello: 0B: Hello:1B: Hello:2B: Hello:3B: Hello:4B: Hello:5A: Hello:0A: Hello:1A: Hello:2A: Hello:3A: Hello:4A: Hello:5
The two running results are inconsistent, indicating that our goal has been achieved
2. Implement runnable
Package Com. bjdata. test; Public Class Runabletest Implements Runnable {string name = "" ; Public Runabletest (string N) {name = N ;} Public Void Run (){ For ( Int I = 0; I <6; I ++ ) {System. Out. println (name + ": Hello:" + I );}} Public Static Void Main (string [] ARGs) {runabletest test1 = New Runabletest ("" ); Runabletest Test2 = New Runabletest ("B" ); Thread thread1 = New Thread (test1); thread thread2 = New Thread (Test2); thread1.start (); thread2.start ();}}
First running result
A: Hello: 0A: Hello:1A: Hello:2A: Hello:3A: Hello:4A: Hello:5B: Hello:0B: Hello:1B: Hello:2B: Hello:3B: Hello:4B: Hello:5
Second run
A: Hello: 0A: Hello:1A: Hello:2B: Hello:0B: Hello:1B: Hello:2B: Hello:3B: Hello:4B: Hello:5A: Hello:3A: Hello:4A: Hello:5
Note: During running, you must first create a thread object, pass the example that requires multi-thread running, and then call the thread run method.