Multi-process: can (concurrently) run multiple tasks (programs) in the operating system
Multithreading: Multiple sequential streams (simultaneous) execution in the same application
Threads (thread) execution process
First generate the thread (NEW), and then enter the ready state (runable), and the time that the CPU executes with the other threads. When the CPU execution time is reached, the running state (Running), the time that the CPU executes during the run may be preempted by other threads, and the thread is ready to wait for the next time it takes to preempt the CPU. A thread may encounter a blocking event while it is running, and then go into a ready state when the blocking state is unblocked. Enter the death state after the thread code has finished running (Dead)
Methods for creating Threads:
Define a thread class, inherit the thread class, and override the Run () method in which the run () method is called the thread body. Because Java only supports single inheritance, classes defined in this way can no longer inherit from other classes.
Class Firstthread extends Thread{public void Run () {for (int i = 0;i < 100;i++) {System.out.println ("firstthread-->" + i);}}}
Class Test{public static void Main (String args[]) {//Generate thread class object Firstthread ft = new Firstthread ();//Start thread, enter ready state, With main thread preemption cpu//ft.run (); can't write like this! Ft.start ();//main thread for (int i =0;i < 100;i++) {System.out.println ("main-->" + i);} Two for loops running in different threads}}
Once you run the test class, there are three threads in the program: main thread, FT thread, garbage collection thread. Main and FT threads run alternately. Multi-threaded operation results are not regular, each result is different
Introduction to Threading