Two ways to implement threading

Source: Internet
Author: User
Tags ticket

1.

There are two ways to implement multithreaded operations in Java: Inheriting the thread class and implementing the Runnable interface

First, inherit the thread class

Class MyThread extends Thread {//Inherit thread class

private String name;

Public MyThread (String name) {

THIS.name = name;

}

public void Run () {//Overwrite the Run method in the thread class

System.out.println ("mythread-->" + name);

}

}

public class Testthread {

public static void Main (String args[]) {

MyThread T1 = new MyThread ("Thread 1");

MyThread t2 = new MyThread ("Thread 2");

T1.start ();//Call Thread Start method

T2.start ();//Call Thread Start method

}

}

Second, realize runnable interface

Class MyThread implements Runnable {

private String name;

Public MyThread (String name) {

THIS.name = name;

}

public void Run () {//Overwrite the Run method in the thread class, which is the principal

System.out.println ("mythread-->" + name);

}

}

public class Testthread {

MyThread t = new MyThread ("thread");

New Thread (t). Start ();

New Thread (t). Start ();

}

Comparison of the two methods

In either case, the start () method is called by the instance of the thread class to begin the execution of the thread, and the start () method executes the thread through the Java Virtual machine calling the Run method defined in the thread. By looking at the definition of the start () method in the Java source program, you can see that it implements multi-threaded operations by invoking the Start0 method of the operating system.

But generally in the development of the system encountered multi-threading situation, to implement the Runnable interface mode as the main way. This is because the way the interface is implemented has many advantages:

1, is by inheriting the thread class way, the thread class can not inherit other classes to implement other functions, the way to implement the interface does not have this limitation;

2. The most important point is that the effect of resource sharing can be achieved by implementing the Runnable interface.

But in fact there are two ways that are closely related:

We create the Mythread class by implementing the interface runnable, and the thread class is also the subclass that implements the Runnable interface. If we want to start a thread, we need to invoke the Run method in the thread class to execute the thread by using the start () method in the thread class and the start () method in the Mythread class. This implementation is a typical proxy pattern.

2.

1. Implement threads in user space

(1) features : The kernel is ignorant of thread packages. From the kernel perspective, it is managed in a normal way, that is, a single-threaded process (there is a runtime system)

(2) Advantages :

User-level thread packages can be implemented on operating systems that do not support threading

The process of saving the thread state and the calling program are only local processes, so it is more efficient to start them than the process kernel calls

No traps, no context switches, no need to flush the memory cache, making thread calls very fast

(3) Disadvantages :

When a thread is blocked by an I/O or a page fault, the kernel blocks the entire process and blocks all threads if it calls a blocking system call, because it does not know that there are multiple threads

Within a single process, there is no clock interruption, so it is impossible to schedule threads in a round-robin manner

2. Implementing threads in the kernel

(1) features :

It makes a system call when a thread wants to create a new thread or undo a wired thread

(2) Advantages :

All calls that can block threads are implemented in the form of system calls, at a considerable cost

When a thread is blocked, the kernel chooses the threads that can run another process, while the runtime system always runs threads in its own process, while the user space implements the thread

Description: Due to the high cost of kernel creation threads, thread recycling

3, the signal is sent to the process and not the thread, when a signal arrives, which thread should be processed by it? Threads can "register" the signals they are interested in. But what happens if two or more threads register the same signal?

Here is the thread pack implementation diagram

4. Hybrid implementation

In this model, each kernel-level thread has a collection of user-level threads that can be used in turn

add: in a user-level thread, the thread table in each process is managed by the runtime system. When a thread transitions to a ready state or blocking state, the information required to restart the thread in the thread table is exactly the same as the information that the kernel holds in the process table

3. Explanation 3

Thread is Process an entity in which the system is independently dispatched and dispatched by the unit, and the thread does not own system resource, which has only a few resources that are essential in the run, it can share all the resources owned by the process with other threads of the same process. One thread can create and revoke Another thread, which can be executed concurrently between multiple threads in the same process. Because of the mutual constraints between threads, the thread is running in a discontinuous.

In the operating system in which threading is introduced, the process is usually used as the basic unit for allocating resources, while threads are used as the basic unit of independent operation and independent Dispatch. Because the thread is smaller than the process, and basically does not have the system resources, the cost of its scheduling is much smaller, and it can improve the degree of concurrent execution among multiple programs in the system, thus significantly improving the utilization and throughput of system resources.

A thread is a single sequential control flow in a program. Running multiple threads at the same time in a single program accomplishes different tasks, called multithreading .

Multithreading is primarily designed to conserve CPU time and play the role of using the computer's memory resources and CPU to run the thread.

Multithreading is to accomplish many tasks synchronously, not to improve the efficiency of the operation, but to improve the efficiency of the use of resources to improve the efficiency of the system. Threads are implemented at the same time when multiple tasks need to be completed.

Java support for multithreading is very powerful, he blocked a lot of technical details, so that we can easily develop multi-threaded applications.

There are 2 ways to implement multi-threading in Java

1 inheriting the Thread class

Class MyThread extends Thread {

public void Run () {

Write the contents of the thread here

}

public static void Main (string[] args) {

Use this method to start a thread

New MyThread (). Start ();

}

}

2 Implementing the Runnable interface

Class MyThread implements runnable{

public void Run () {

Write the contents of the thread here

}

public static void Main (string[] args) {

Use this method to start a thread

New Thread (New MyThread ()). Start ();

}

}

It is generally encouraged to use the second method, because Java only allows single inheritance, but allows multiple interfaces to be implemented. The second method is more flexible.

For example: The second method

public class TestThread1 {

public static void Main (string[] args) {

Runner1 r = new Runner1 ();
R.run ();
Thread t = new Thread (r);
T.start ();

for (int i=0; I <100; i++)
System.out.println ("Main Thread:--------" + i);
}
}

Class Runner1 implements Runnable {//Implements Runnable interface, interfaces are used, interface is flexible
public void Run () {
for (int i=0; I <100; i++)
System.out.println ("Runner1:" + i);
}
}

The first of these methods

public class TestThread1 {

public static void Main (string[] args) {
Runner1 r = new Runner1 ();
R.start ();

for (int i=0; I <100; i++)
System.out.println ("Main Thread:--------" + i);
}
}

Class Runner1 extends Thread {//Inherit thread class

public void Run () {
for (int i=0; I <100; i++)
System.out.println ("Runner1:" + i);
}
}

4. Explanation 4

There are two ways to implement multithreading in Java. The first is the direct inheritance of the thread class, and the second is to implement Runnable interface. So what is the difference between the two ways of implementing multithreading?

To answer this question, we can write a piece of code to analyze. We use the code to simulate the railway ticketing system, to achieve the sale of a day by four ticket sales of a train 100 tickets, a ticket point with a thread.

We begin by writing this procedure:

Java code
    1. Class ThreadTest extends thread{
    2. private int ticket = 100;
    3. public Void Run () {
    4. While (true) {
    5. if (Ticket > 0) {
    6. System.out.println (Thread.CurrentThread (). GetName () +
    7. "is saling ticket" + ticket--);
    8. }else{
    9. Break ;
    10. }
    11. }
    12. }
    13. }


Main test class:

Java code
      1. Public class threaddome1{
      2. public static void Main (string[] args) {
      3. ThreadTest t = new ThreadTest ();
      4. T.start ();
      5. T.start ();
      6. T.start ();
      7. T.start ();
      8. }
      9. }


In the above code, we use the ThreadTest class to simulate the ticket sales process, each cycle of the run method will reduce the total number of votes by 1, simulated sell a ticket, and the car ticket number printed out, directly remaining votes to zero so far. In the main method of the ThreadDemo1 class, we created a thread object and started it repeatedly four times, hoping to generate four threads in this way. From the running results we found that only one thread is running, the result tells us: A thread object can only start a thread, no matter how many times you call the start () method, the result is only one thread.

We then modified the THREADDEMO1 to create four thread objects in the Main method:

Java code
      1. Public class threaddemo1{
      2. public static void Main (string[] args) {
      3. new ThreadTest (). Start ();
      4. new ThreadTest (). Start ();
      5. new ThreadTest (). Start ();
      6. new ThreadTest (). Start ();
      7. }
      8. }


Java code
    1. Class ThreadTest extends thread{
    2. private int ticket = 100;
    3. public Void Run () {
    4. While (true) {
    5. if (Ticket > 0) {
    6. System.out.println (Thread.CurrentThread (). GetName () +
    7. "is saling ticket" + ticket--);
    8. }else{
    9. Break ;
    10. }
    11. }
    12. }
    13. }



Is this the end of the meeting?

The results show that each ticket is printed four times, that is, four threads each sell their own 100 tickets, instead of selling a common 100 tickets. How is this situation caused? What we need is that multiple threads deal with the same resource, a resource can only correspond to one object, in the above program, we create four threadtest objects, it is equal to create four resources, each resource has 100 tickets, each thread is working on its own resources.

Through these experiments and analysis, it can be concluded that to achieve this railway ticketing process, we can only create a resource object, but to create multiple threads to process the same resource object, and each thread is running the same program code. Review the process of writing multithreading using interfaces.

Java code
    1. public class  threaddemo1{  
    2.   public  static void main (string[] args) {  
    3.     threadtest t = new  ThreadTest ();   
    4.     new thread (t). Start ();   
    5.     new thread (t). Start ();   
    6.     new thread (t). Start ();   
    7.     new thread (t). Start ();  
    8.   }  
    9. }  


Java code
    1. Class ThreadTest implements runnable{
    2. private int tickets = 100;
    3. public Void Run () {
    4. While (true) {
    5. if (Tickets > 0) {
    6. System.out.println (Thread.CurrentThread (). GetName () +
    7. "is saling ticket" + tickets--);
    8. }
    9. }
    10. }
    11. }



In the above program, four threads were created, each calling the run () method in the same ThreadTest object, accessing an instance of the variable (tickets) in the same object, which satisfies our needs. You can start multiple Notepad programs on Windows, which means that multiple processes use the same Notepad program code.

It can be seen that implementing the Runnable interface has the following notable benefits over inheriting the thread class:

(1) Suitable for multiple threads of the same program code to handle the same resource situation, the virtual CPU (thread) and the Code of the program, the data effectively separated, better reflect the object-oriented design ideas.

(2) can avoid limitations due to the single inheritance of Java. We often encounter the case that when we want to put a subclass of a class that has been inherited into a multi-threaded, because a class can not have two parent classes at the same time, so can not inherit the thread class, then this class can only adopt the way of implementing the Runnable interface.

(3) It is advantageous to the robustness of the program, the code can be shared by multiple threads, and the code and data are independent. When multiple threads execute code from an instance of the same class, they are said to share the same code. Multiple threads manipulate the same data, regardless of their code. When shared access is the same object, that is, they share the same data. When a thread is constructed, the required code and data are passed in through an object as a constructor argument, an instance of a class that implements the Runnable interface.

Two ways to implement threading

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.