Relation between Thread and Runnable

The Thread class is an implementation of the interface Runnable.

public class Thread implements Runnable 
Copy the code

Source code analysis

  • The Thread Threa class calls the start() method.

private native void start0()
Copy the code

Native indicates that the method is a native function, that is, the function is implemented in C/C++, compiled into a DLL, and called by Java. The native method is registered with the Thread object initialization, as shown in the figure. In the static block Static natives method, there is a registerNatives method, which registers some local methods for the Thread class to use.

The start0 method creates a new thread in the JVM

  • Runnable The Runnable interface has only one run() method, which is completely thread run specification.

Code Example Analysis

  • The Thread class defines a class that sells tickets
public class TicketThread extends Thread {

    private int ticket = 100000;

    @Override
    public void run() {
        for (int i = 0; i < 100000; i++) {
            if (ticket > 0) {
                System.out.println("ticket=" + ticket-- + ","+ Thread.currentThread().getName()); }}}}Copy the code

Start three threads

new TicketThread().start();
new TicketThread().start();
new TicketThread().start();
Copy the code

Each thread performs the task of selling tickets independently, and the number of votes in each thread decreases by 1.

  • The Runnable interface implements a class that sells tickets
public class TicketRunnableThread implements Runnable {
    private int ticket = 1000;
    public void run() {
        for (int i = 0; i < 1000; i++) {
            if (ticket > 0) {
                System.out.println("ticket=" + ticket-- + ","+ Thread.currentThread().getName()); }}}}Copy the code

Start three threads

TicketRunnableThread ticketRunnableThread = new TicketRunnableThread();
new Thread(ticketRunnableThread).start();
new Thread(ticketRunnableThread).start();
new Thread(ticketRunnableThread).start();
Copy the code

Three threads work together to complete the ticket selling task. However, three threads work together to execute the same code, resulting in thread insecurity, which can be solved by locking.

Used to choose

  • While implementing the Runnable interface, you can also inherit from other classes, avoiding the limitations of Java’s single-inheritance nature.
  • The Runnable interface implements resource sharing, but Thread cannot.