In the previous article, I introduced the implementation method of Java multi-threading. Through this article, I will introduce Java multi-threading examples to you. Friends who are interested in Java multi-threading will learn together.
First of all, let me tell you the advantages and disadvantages of multi-threading
Advantages of multithreading:
1) Better resource utilization
2) Programming is simpler in some cases
3) The program responds faster
The cost of multithreading:
1) More complex design
While 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 generated by incorrect thread synchronization are very difficult to detect and reproduce to fix.
2) Overhead of context switching
When the CPU switches from executing one thread to executing another thread, it needs to first store the local data of the current thread, program pointers, etc., then load the local data of another thread, program pointers, etc., 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, context switching should be reduced.
There are two key technologies for defining and starting threads:
First: The thread class must implement the java.lang.Runnable interface or inherit the java.lang.Thread class, and both must implement the run method, where the run method has no input, no output, and no exceptions.
Second: Call the start method of the Thread class to start the thread. After obtaining the CPU resources, the start method automatically calls the thread run method to start running.
package test;import java.util.Vector;import java.util.Date;/** * Thread test instance* @author Still flowing* */public class Threadnew{ /** * * @author Still The flow of water* */ class ThreadA extends Thread{ private Date runtime; public void run() { System.out.println("ThreadA begin."); this.runtime = new Date(); System.ou t.println("ThreadA end."); } }/** * * @author Still flowing water* */class ThreadB implements Runnable{ private Date runtime; public void run() { System.out.println("ThreadB begin.") ; this.runtime = new Date( ); System.out.println("ThreadB end."); } }/** * */public void starta(){ Thread threada = new ThreadA(); threada.start();}/** * * */public void startb(){ Runnable threadb = new ThreadB(); Thread thread = new Thread(threadb); thread.start(); }/** * * @param args */public st atic void main(String[] args){ Threadnew test = new Threadnew(); test.starta(); test.startb();}}