Java multithreaded instance

  • 2020-04-01 04:20:29
  • OfStack

In the last article to introduce you (link: #), through this article to introduce you to Java multithreading example, interested in Java multithreading friends to learn together

First, let's talk about the advantages and disadvantages of multithreading

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 requires special attention when multiple threads access Shared data. Interactions between threads are often very complex. Errors caused by incorrect thread synchronization are very difficult to detect and reproduce to fix.

2) the overhead of context switching

When the CPU switches from executing one thread to executing another, it needs to store the local data of the current thread, the program pointer, etc., and then load the local data of the other thread, the program pointer, etc., before starting execution. This switch is called a "context switch". The CPU executes one thread in one context and then switches to execute another thread in another context. Context switching is not cheap. Context switching should be reduced if it is not necessary.

There are two key techniques for defining and starting threads:

First: the Thread class must implement the java.lang.runnable interface or inherit from 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. When CPU resources are obtained, the start method automatically calls the Thread run method to start running.


package test;
import java.util.Vector;
import java.util.Date;

public class Threadnew
{
 
class ThreadA extends Thread
{
 private Date runtime;
 public void run()
 {
 System.out.println("ThreadA begin.");
 this.runtime = new Date();
 System.out.println("ThreadA end.");
 }
 }

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();
 }

public static void main(String[] args)
{
 Threadnew test = new Threadnew();
 test.starta();
 test.startb();
}
}


Related articles: