Thread and Runable comparison

In most cases, regardless of the way the code is written, both of them can realize multithreading. So the difference between them is not the difference in performance and function, but the difference in writing style, code maintainability, loose coupling and convenient operation.

1. The most direct difference is that Runable is an interface that supports multiple inheritance, that is, implementation classes can also implement other interfaces, reducing coupling. And Tread is a class, which can only be inherited by a single class, so its subclass can no longer inherit other classes, increasing the coupling.

2. It is more convenient to write a runable. You only need to implement a run method, or even do not need to create a new subclass. You can directly define an anonymous implementation class in the method. Thread writing is more complex. To create a new subclass, implement start(), construct methods, etc.

3. It is more convenient to share variables with runable, which can separate shared variables from thread code and thread creation, better achieve low coupling effect, and better control the synchronization of shared variables.

Example:

Code from: https://www.cnblogs.com/yangdy/p/5274455.html

It's not easy to share because of multithreading and variable access in the way of tree

public class Main {

    public static void main(String[] args) {
        MyThread T1 = new MyThread("A");
        MyThread T2 = new MyThread("B");
        T1.start();
        T2.start();


    }

}

 class MyThread extends Thread {
    private String name;
    public MyThread(String name) {
        this.name = name;
    }
    
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(name+":"+i);
            try {
                sleep(1000); //Sleep for 1 second, avoid too fast to see simultaneous execution
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
    }
}

Realize multithreading and share variables in the running mode

public class Main {

    public static void main(String[] args) {

        //Test Runnable
        MyThread1 t1 = new MyThread1();
        new Thread(t1).start();//If the same t1 is not available in Thread, an error will be reported
        new Thread(t1).start();
        new Thread(t1).start();

    }

}
class MyThread1 implements Runnable{
    private int ticket = 10;
    @Override
    //Remember to make the resources public, and add the synchronized keyword before the run method, otherwise resources will be robbed
    public synchronized  void  run() {
        for (int i = 0; i <10; i++) {
            if (this.ticket>0) {
                System.out.println("Selling tickets: ticket"+this.ticket--);
            }
        }
        
    }
    
}

Running mode is generally recommended

 

Posted on Fri, 08 Nov 2019 07:50:34 -0800 by jmandas