Java has two ways to implement multithreading and the difference between the two methods

Source: Internet
Author: User

Java has two ways to implement multithreading and the difference between the two methods
It is widely spread on the Internet that an online ticket sales system has explained and forwarded it. I don't know where the original article actually came from. Java has two ways to implement multithreading. One is to inherit the Thread class directly, and the other is to implement the Runnable interface. So what are the differences between the two multithreading methods in applications? To answer this question, we can write a piece of code for analysis. We use code to simulate the railway ticket sales system and sell 100 tickets for a certain train on a certain day at four ticket sites. One ticket point is represented by one thread. First, we will write this program: Java code

class ThreadTest extends Thread{    private int ticket = 100;    public void run(){      while(true){        if(ticket > 0){          System.out.println(Thread.currentThread().getName() +            "is saling ticket" + ticket--);        }else{          break;        }      }    }  }  

 

Main test class: Java code
public class ThreadDome1{    public static void main(String[] args){      ThreadTest t = new ThreadTest();      t.start();      t.start();      t.start();      t.start();    }  }  

 

In the above Code, we use the ThreadTest class to simulate the ticket sales process. In each cycle of the run method, the total number of votes is reduced by 1, and a ticket is sold. At the same time, the ticket number is printed out, the number of remaining votes is zero. In the main method of the ThreadDemo1 class, we create a thread object and start it four times again. In this way, we hope to generate four threads. From the running results, we found that only one thread is running. This result tells us that a thread object can only start one thread, no matter how many times you call the start () method, only one thread is returned. We then modify ThreadDemo1 and create four Thread objects in the main method: Java code
public class ThreadDemo1{    public static void main(String[] args){      new ThreadTest().start();      new ThreadTest().start();      new ThreadTest().start();      new ThreadTest().start();    }  }  

 

Java code
class ThreadTest extends Thread{    private int ticket = 100;    public void run(){      while(true){        if(ticket > 0){          System.out.println(Thread.currentThread().getName() +              " is saling ticket" + ticket--);        }else{          break;        }      }    }  }  

 

Is this achieved? From the result, each ticket number is printed four times, that is, each of the four threads sells their own 100 tickets, rather than the same 100 tickets. How did this happen? What we need is that multiple threads can manage the same resource. One resource can only correspond to one object. In the above program, we have created four ThreadTest objects, which is equivalent to four resources, each resource has 100 tickets, and each thread is processing its own resources. After these experiments and analyses, we can conclude that to implement this railway ticket sales program, we can only create one resource object, but we need to create multiple threads to process the same resource object, the same program code is run on each thread. Review the process of using interfaces to write multithreading. Java code
public class ThreadDemo1{    public static void main(String[] args){      ThreadTest t = new ThreadTest();      new Thread(t).start();      new Thread(t).start();      new Thread(t).start();      new Thread(t).start();    }  }  

 

Java code
class ThreadTest implements Runnable{    private int tickets = 100;    public void run(){      while(true){        if(tickets > 0){          System.out.println(Thread.currentThread().getName() +            " is saling ticket " + tickets--);        }      }    }  }  

 

In the above program, four threads are created. Each thread calls the run () method in the same ThreadTest object and accesses the instance of variable (tickets) in the same object, this program meets our needs. In Windows, you can start multiple notepad programs, that is, multiple processes use the same Notepad program code. It can be seen that implementing the Runnable interface has the following significant advantages over inheriting the Thread class: (1) it is suitable for multiple threads with the same program code to process the same resource, effectively separating virtual CPU (thread) from program code and data reflects the object-oriented design idea. (2) avoid restrictions caused by Java's single inheritance feature. We often encounter this situation, that is, when we want to put sub-classes that have inherited a class into multithreading, because a class cannot have two parent classes at the same time, therefore, we cannot inherit the Thread class, so this class can only implement the Runnable interface. (3) It is conducive to program robustness. The code can be shared by multiple threads, and the code and data are independent. When the Execution Code of multiple threads comes from instances of the same class, that is, they share the same code. The data operated by multiple threads is independent of their code. When shared access has the same object, that is, they share the same data. When a thread is constructed, the required code and data are passed through an object as the real parameter of the constructor. This object is an instance of the class that implements the Runnable interface.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.