What is the difference between implementation method and inheritance method?
*the difference:
*Inherited Thread: thread code is stored in the run method of the Thread subclass
*Implement Runnable: thread code is stored in the run method of the subclass of the interface
* Benefits of implementation: Avoid the limitations of single inheritance
* When defining threads, it is recommended to use implementation method. Of course, if a class does not inherit the parent class, then multi-threading can also be implemented by inheriting the Thread class.
*Note: The Runnable interface does not throw an exception, so the class that implements it can only be try-catch and cannot throw
*Java provides a professional solution to the security problem of multithreading, which is to synchronize the code block synchronized (object){code that needs to be synchronized}
*Precautions for synchronization:
*1. There are 2 or more threads
*2. Multiple threads use one lock (object)
* Benefits of synchronization: Solve multi-threaded security issues
* Disadvantages of synchronization: multiple threads need to judge the lock, which consumes more resources
package multithreading; class Ticket implements Runnable{//private static int tick = 100;private int tick=100;Object obj = new Object();//Create an image or rewrite a class yourself to create an object. The following synchronizes the keywords need to be used @Overridepublic void run() {while(true){synchronized(obj)//synchronized(this){if(tick>0){try {Thread.sleep(10);} catch (Exception e) {}System.out.println(Thread.currentThread().getName()+"...Sales: "+(tick--)+"Title");//tick--;}else {break;}}}}} public class Test {public static void main(String[] args) {Ticket t = new Ticket();//Create a class that implements the Runnable interface//Create 4 multithread objects and pass the above interface object to its constructor Thread t1 = new Thread(t);//Create a thread Thread t2 = new Thread(t);//Create a thread Thread t3 = new Thread(t);//Create a thread Thread t4 = new Thread(t);//Create a thread //Open thread t1.start();t2.start();t3.start();t4.start();}}The above is the full content of the two ways to implement multi-threading Java to inherit the Thread class and the method to implement the Runnable interface. I hope it will be helpful to everyone and support Wulin.com more~