Both methods should be familiar, putting code that requires parallel processing in the run () method, and thestart () method starts the thread to automatically invoke the run () method .
This is regulated by the Java Memory mechanism. and the run () method must be public access and the return value type is void. Multithreading is the use of CPU time-sharing,
Macro allows all threads to execute together, also called concurrency.
There are two ways to implement and start a thread
1. Write a class to inherit from the thread class and rewrite the Run method. Start the thread with the Start method;
2, write a class implementation runnable interface, implementation Run method. Starts with the new Thread (Runnable target). Start () method.
Start
Start the thread with the Start method, which really implements multithreading, without waiting for the Run method body code to complete and proceed directly to the following code.
Start a thread by invoking the start () method of the thread class, at which point the thread is in a ready (running) state and is not running.
Once you get the SPU time slice, you start executing the run () method, where method run () is called the thread body, which contains the contents of the thread to execute.
The Run method ends and the thread terminates.
After calling start (), the thread is placed in the wait queue, waiting for the CPU to dispatch, and does not have to start immediately, just put the thread in the movable line state.
The thread thread then invokes the run () method through the JVM, executing the thread body of this thread. That is, call run after calling start.
Run:
The run () method is just a common method of a class, and if you call the Run method directly, there is still only the main thread in the program,
Does the program execution path still have only one, or do you want to execute sequentially, or wait until the Run method body finishes execution before you can continue with the following code?
This does not achieve the purpose of multiple threads.
code example:
Package Com.itheima;
public class Demo2 {public
static void Main (string[] args) {
Runner1 runner1 = new Runner1 ();
Runner2 runner2 = new Runner2 (); thread (Runnable target) assigns a new thread object.
thread thread1 = new Thread (runner1);
Thread thread2 = new Thread (runner2);
Thread1.start ();
Thread2.start ();
Thread1.run ();
Thread2.run ();
}
Class Runner1 implements Runnable {public
void run () {for
(int i = 0; i < i++) {
System.out.print ln ("Enter Runner1 Run State ——————————" + i);
}
}
Class Runner2 implements Runnable {public
void run () {for
(int i = 0; i < i++) {
System.out.print ln ("Enter Runner2 Run State ==========" + i);
}
}