review

In the last article on Java Basics threads, we introduced the concepts of threads and processes, and left a topic: three Windows selling 100 tickets at the same time, so today we will talk about the implementation of multithreaded programming.

There are two main methods to construct multithreading: inheritance and implementation

Multithreaded creation

1. Inherit the Thread class

The inherited approach is to build a class that inherits from Thread and implements the run method, as follows

class SubThread extends  Thread{
    @Override
    public void runSubThread SubThread =new SubThread(); // Create instance subthread.start (); // The thread startsCopy the code
  • The start method starts the thread and executes the corresponding run method
  • You need to place the business code that needs to be implemented in the Run method

2. Implement the Runnable interface

Implement the java.lang.Runnable interface

Class SubThread implements Runnable{// Create a class that implements Runnable @override public voidrunSubThread subThread1=new SubThread(); Thread t1=new Thread(subThread1); // Get a Thread instance t1.start(); // Call the start method of the thread instanceCopy the code

Several important steps

  • 1 Build a class that implements the Runnable interface
  • 2 rewrite the run method to write your business code
  • Build the class instance and get the Thread instance when the argument is passed to the Thread class constructor
  • 4 The thread instance invokes the start method

3. Some basic methods of the Thred class

Thread.currentthread () // get the currentThread // these are all methods on Thread instancessetName(); // Set the thread name getName(); // Get the thread name yield(); Join (); // Call the join method of another thread in one thread's execution, which means that the target thread executes immediately and returns to the original thread isAlive() after execution; // check whether the current thread is alive. // Display the thread to sleepsetPriority()// Sets the Priority of the current thread getPriority()// Gets the Priority of the current threadCopy the code

4. Compare inheritance and implementation

All related to the Runnable interface

The business object code is placed in the run method

In view of the characteristics of Java singleton interface implementation is more universal

Implementation is more appropriate if multiple threads are working on the same resource

Selling tickets program

In the last post we left a problem: there are three Windows selling tickets, a total of 100 tickets, let’s implement it

1. Inheritance method

Class Window extends Thread{static int ticket=100; @Override public voidrun() {
        while (true) {if(ticket>0){
                System.out.println(Thread.currentThread().getName()+"Ticket number: :"+ ticket--);
            }else{
                break; }}}} // Create three thread instances Window w1=new Window(); Window w2=new Window(); Window w3=new Window(); w1.setName("Window 1");
w2.setName("Window 2");
w3.setName("Window 3");
w1.start();
w2.start();
w3.start();
Copy the code

Since 100 tickets are sold, we need to set ticket to static and share this data with three threads

2. Implementation method

Class Window implements Runnable{// implement interface int ticket=100; @Override public voidrun() {
        while (true) {if(ticket>0){
                System.out.println(Thread.currentThread().getName()+"Ticket number: :"+ ticket--);
            }else{
                break; }}}} // Create three thread instances Window w=new Window(); Thread t1=new Thread(w); Thread t2=new Thread(w); Thread t3=new Thread(w); t1.setName("Window 1");
t2.setName("Window 2");
t3.setName("Window 3");
t1.start();
t2.start();
t3.start();
Copy the code

Note: Since there is only one Window instance, there is only one ticket=100, no static modifier is required

Advantages and disadvantages of multithreaded programs

In the single-core era, multi-threading causes thread switching losses, but even then multi-threading makes more sense for graphical interfaces, which enhance the user experience. (For example, if you’re writing code on a single-core machine while listening to music) multiple threads are actually switching back and forth across the CPU, giving you the illusion of parallelism.

In the multi-core era, for example, the current 8-generation I7 processor has 6 cores and 12 threads, which can maintain parallel operation of multiple threads and greatly improve performance. Multi-threaded programming can improve the utilization rate of COMPUTER CPU

In addition, multithreaded programming can improve the program structure, long and complex process can be divided into multiple threads, independent running, easy to understand and modify

conclusion

Today mainly explains how to achieve multithreading, and thread instances on what methods, need to focus on the grasp of the implementation of the way, because the implementation of the way to avoid the shortcomings of Java single inheritance.

However, the sample code in this article is not thread-safe, which we will cover in the next article.

If you like this article, please click on the subscription number “My Programming Notes” for more content