Java multithreading --- basic, java multithreading ---
I. java multithreading-threads and processes
Process: the execution process of a program (task), with resources (shared memory, shared resources) and threads (one or more, at least one ). For example, open the task manager, qq, and chrome, all belong to processes.
Thread: The smallest Execution Unit in the system. The same process has multiple threads, and the threads share the resources of the process. For example, qq chat sends messages.
Single thread: there is only one thread in the program. In fact, the main method is a main thread.
Multithreading: The program runs multiple tasks to better use cpu resources.
2. java multithreading-thread implementation
Simply put, inherit the Thead class or implement the Runnable interface, and then override the run method in it.
Inherit Thead class
1 public class MyThead extends Thread{ 2 3 private String name; 4 public MyThead(String name) { 5 this.name = name; 6 } 7 @Override 8 public void run() { 9 for (int i = 0; i < 1000; i++) {10 System.out.println(name+"------"+i);11 }12 }13 }
Implement the Runnable interface
1 public class MyRunnable implements Runnable{ 2 3 private String name; 4 public MyRunnable(String name) { 5 this.name = name; 6 } 7 @Override 8 public void run() { 9 for (int i = 0; i < 1000; i++) {10 System.out.println(name+"----"+i);11 }12 13 }14 15 }
Start thread
1 public class TheadDemo { 2 3 public static void main(String[] args) { 4 MyThead t1 = new MyThead("t1"); 5 MyThead t2 = new MyThead("t2"); 6 7 t1.start(); 8 t2.start(); 9 10 MyRunnable r1 = new MyRunnable("r1");11 MyRunnable r2 = new MyRunnable("r2");12 13 Thread t3 = new Thread(r1);14 Thread t4 = new Thread(r2);15 16 t3.start();17 t4.start();18 }19 }
Iii. java multithreading-thread status
Creation status: Creates a multi-threaded object.
Ready status: Call start () and wait for the cpu to call.
Running status: run ().
Blocking status: the execution is stopped temporarily and resources are handed over to other threads for use.
Termination status: the thread ends.
4. java multithreading-common methods (in thead class)
Get current thread object currentThread ()
Get the thread name getName ()
Determine whether the thread is running isAlive ()
For example, when two threads t1 and t2 are executed forcibly, t2 calls the join () method, t1 is paused, and t2 is executed, after the execution is complete, release the resource and run T1.
Sleep () of a thread. For example, if t1 is executed every time, wait for 5 seconds for t1.sleep (5000)
For example, when two threads t1 and t2 are executed at t1, t1 calls the yield () method, t1 stops and t2, after the execution is complete, release the resource and run T1.