Java threads (1)
1. Process and thread
Multi-process:
Multiple tasks (programs) can be run in the operating system at the same time)
Multithreading:
Multiple sequential streams (at the same time) are executed in the same application.
2. multi-threaded program running mode
3. Define the thread method
Method 1:
Defines a Thread class, which inherits the class Thread and overwrites the method run (). The method run () is called the Thread body;
Because Java only supports single inheritance, classes defined using this method cannot inherit other classes.
Class FirstThread extends Thread {public void run () {for (int I = 0; I <100; I ++) {System. out. println ("FirstThread -->" + I );}}}Note: This program has three threads.
1. The main function is a thread.
2. the ft thread object is the second thread after startup
3. Garbage collection mechanism thread
Class Test {public static void main (String args []) {// the object that generates the Thread class FirstThread ft = new FirstThread (); // start the thread ft. start ();}}Test. Add a for loop to the Test class.
Class Test {public static void main (String args []) {// the object that generates the Thread class FirstThread ft = new FirstThread (); // start the thread (start () is required ()) ft. start (); for (int I = 0; I <100; I ++) {System. out. println ("main -->" + I );}}}After running, two loops are found to run alternately, indicating that the two loops are in different threads.