Home  >  Article  >  Java  >  Example code sharing of two methods for creating threads in Java

Example code sharing of two methods for creating threads in Java

黄舟
黄舟Original
2017-03-17 10:48:591368browse

This article mainly introduces the detailed explanation and examples of the two methods of creating threads in Java. Friends in need can refer to the following

Two methods of creating threads in Java

Java provides the thread class Thread to create multi-threaded programs. In fact, the operation of creating a thread is the same as creating an ordinary class object, and a thread is an instance object of the Thread class or its subclass. Each Thread object describes a separate thread. To generate a thread, there are two methods:

◆You need to derive a new thread class from the Java.lang.Thread class and overload its run() method;

◆Implement Runnalbeinterface and overload the run() method in Runnalbe interface.

Why does Java provide two methods to create threads? What are the differences between them? In comparison, which method is better?

In Java, classes only support single inheritance, that is, when defining a new class, it can only extend an external class. In this way, if you create a custom thread class It is implemented by extending the method of the Thread class, so this custom class cannot extend other classes, and it cannot implement more complex functions. Therefore, if a custom class must extend other classes, you can use the method that implements the Runnable interface to define the class as a thread class, thus avoiding the limitations of Java single inheritance.

The most important thing is that threads created by implementing the Runnable interface can process the same resource, thereby realizing resource sharing.

(1) By extending the Thread class Create multi-threads

Suppose a theater has three ticket outlets, which are used to sell tickets to children, adults and the elderly. The theater has 100 movie tickets for each window, which are children's tickets, adult tickets and senior tickets. Three windows need to sell tickets at the same time, and now there is only one ticket seller. This ticket seller is equivalent to a CPU, and three windows are equivalent to three threads. Let’s take a look at how these three threads are created through the program.

public class MutliThreadDemo {
 public static void main(String [] args){
  MutliThread m1=new MutliThread("Window 1");
  MutliThread m2=new MutliThread("Window 2");
  MutliThread m3=new MutliThread("Window 3");
  m1.start();
  m2.start();
  m3.start();
 }
}
class MutliThread extends Thread{
 private int ticket=100;//每个线程都拥有100张票
 MutliThread(String name){
  super(name);//调用父类带参数的构造方法
 }
 public void run(){
  while(ticket>0){
   System.out.println(ticket--+" is saled by "+Thread.currentThread().getName());
  }
 }
}

A thread class is defined in the program, which extends the Thread class. Use the extended thread class to create three thread objects in the main method of the MutliThreadDemo class, and start them respectively through the start() method.

As you can see from the results, each thread corresponds to 100 movie tickets, and there is no relationship between them. This means that each thread is equal and has no priority relationship, so they all have opportunities. Get CPU processing. However, the results show that these three threads are not executed alternately in sequence, but when the three threads are executed at the same time, some threads have more chances to be allocated time slices, and the tickets are sold out in advance, while some threads are allocated time. There are fewer opportunities to film, and tickets will be sold out later.

It can be seen that multiple threads created by extending the Thread class, although executing the same code, are independent of each other, and each has its own resources without interfering with each other.

(2) Create multi-threads by implementing the Runnable interface

public class MutliThreadDemo2 {
 public static void main(String [] args){
  MutliThread m1=new MutliThread("Window 1");
  MutliThread m2=new MutliThread("Window 2");
  MutliThread m3=new MutliThread("Window 3");
  Thread t1=new Thread(m1);
  Thread t2=new Thread(m2);
  Thread t3=new Thread(m3);
  t1.start();
  t2.start();
  t3.start();
 }
}
class MutliThread implements Runnable{
 private int ticket=100;//每个线程都拥有100张票
 private String name;
 MutliThread(String name){
  this.name=name;
 }
 public void run(){
  while(ticket>0){
   System.out.println(ticket--+" is saled by "+name);
  }
 }
}

Since these three threads are also independent of each other, each has its own resources, that is, 100 movie tickets, so the output result of the program is similar to the result of (1). Each thread processes its own 100 tickets independently without affecting each other.

It can be seen that as long as the actual situation requires that the newly created threads are independent of each other, have their own resources, and do not interfere with each other, any method can be used to create multi-threads. Because multi-threaded programs created in these two ways can achieve the same function.

Since these three threads are independent of each other and each has its own resources, namely 100 movie tickets, the results output by the program are similar to those in Example 4.2.1. Each thread processes its own 100 tickets independently without affecting each other.

It can be seen that as long as the actual situation requires that the newly created threads are independent of each other, have their own resources, and do not interfere with each other, any method can be used to create multi-threads. Because multi-threaded programs created in these two ways can achieve the same function.

(3) Realize resource sharing between threads by implementing the Runnable interface

Such situations also exist in reality, such as simulating the ticketing system of a train station. If There are only 100 train tickets sent from point A to point B that day, and all windows are allowed to sell these 100 tickets, then each window is also equivalent to a thread, but the difference from the previous example is that all thread processing The resource is the same resource, that is, 100 tickets. If we still use the previous method to create threads, it is obviously impossible to implement. How to deal with this situation? Look at the following program, the program code is as follows:

public class MutliThreadDemo3 {
 public static void main(String [] args){
  MutliThread m=new MutliThread();
  Thread t1=new Thread(m,"Window 1");
  Thread t2=new Thread(m,"Window 2");
  Thread t3=new Thread(m,"Window 3");
  t1.start();
  t2.start();
  t3.start();
 }
}
class MutliThread implements Runnable{
 private int ticket=100;//每个线程都拥有100张票
 public void run(){
  while(ticket>0){
   System.out.println(ticket--+" is saled by "+Thread.currentThread().getName());
  }
 }
}

As a result, as analyzed earlier, the program only creates one resource in the memory, and the three newly created threads are all based on accessing the same resource. And because the same code is running on each thread, they perform the same function.

It can be seen that if the real-life problem requires the creation of multiple threads to perform the same task, and the multiple threads will share the same resource, then you can create a multi-threaded program by implementing the Runnable interface. This function cannot be achieved by extending the Thread class. Readers think about it, why?

Implementing the Runnable interface has incomparable advantages over extending the Thread class. This method is not only conducive to the robustness of the program, allowing the code to be shared by multiple threads, but also the code and data resources are relatively independent, which is particularly suitable for situations where multiple threads with the same code process the same resource. In this way, threads, code and data resources are effectively separated, which well reflects the idea of ​​Object-oriented programming. Therefore, almost all multi-threaded programs are completed by implementing the Runnable interface.

The above is the detailed content of Example code sharing of two methods for creating threads in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn