Multithreading programming in Java
1、 Advantages and disadvantages of multithreading
Advantages of multithreading:
1) Better resource utilization 2) simpler programming in some cases 3) faster program response
Cost of multithreading:
1) The design is more complex. Although some multithreaded applications are simpler than single threaded applications, others are generally more complex. This part of the code needs special attention when accessing shared data through multiple threads. The interaction between threads is often very complex. Errors caused by incorrect thread synchronization are very difficult to find and reproduce for repair.
2) Context switching overhead when the CPU switches from executing one thread to executing another thread, it needs to first store the local data and program pointer of the current thread, then load the local data and program pointer of another thread, and finally start execution. This switching is called "context switch". The CPU executes a thread in one context and then switches to another context to execute another thread. Context switching is not cheap. If not necessary, the occurrence of context switching should be reduced.
2、 Create Java multithreading
1. Create a subclass of thread
Create an instance of the thread subclass and override the run method, which will be executed after calling the start () method. Examples are as follows:
public class MyThread extends Thread { public void run(){ System.out.println("MyThread running"); } }MyThread myThread = new MyThread();
myTread.start();