What's the difference between how you implement and how you inherit?
Difference
* Inheritance Thread: Thread code is stored in the thread subclass Run method
* Implement runnable: The thread code is stored in the Run method of the subclass of the interface
* Benefits of implementation: avoiding the limitations of single inheritance
* When defining a thread, it is recommended to use the implementation method, of course, if a class does not inherit the parent class, you can also implement multithreading by inheriting the thread class
* Note: The runnable interface does not throw an exception, then the class that implements it can only be try-catch not throws
*java provides a professional solution to multithreading security problems by synchronizing code blocks synchronized (objects) {code that needs to be synchronized}
* The premise of synchronization:
*1. has 2 threads and more
*2. Multiple threads using a lock (object)
* Benefits of synchronization: solves the problem of multithreading security
* Synchronization of the drawbacks: multiple threads need to determine the lock, more consumption of resources
Package multithreading;
Class Ticket implements Runnable
{
// private static int tick =;
private int tick=100;
Object obj = new Object ()//Create an image or write a new class for yourself creating an object The following synchronization keyword requires
@Override public
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--) +" Ticket "); 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 multithreaded objects and pass the above interface object to its constructor
thread t1 = new Thread (t);//create thread threads
t2 = new Thread thread (t);//created a threading threads
t3 = new Thread (t);//create thread thread
T4 = new Thread (t);//Create a thread
//Open thread
T1.start ();
T2.start ();
T3.start ();
T4.start ();
}
The above is a small series for you to bring the Java implementation of multithreading two ways to inherit the thread class and the implementation of the runnable interface of the whole content of the method, I hope to help you, a lot of support cloud Habitat Community ~