Runnable and Thread implement multi-Thread and Runnable synchronization resource sharing, runnablethread
(1)
There are two ways to implement Multithreading
(1)
Inherit the Thread class and override the run () method, as shown in the following example:
Class MyThread extends Thread {
Public void run (){
//
}
}
Class Main {
Public void main (String [] args ){
MyThread thread = new Mythread ();
Thread. start ();
}
}
(2)
Using the runnable interface
Class MyThread implements Runnable {
Public void run (){
//
}
}
Class Main {
Public static void main (String [] args ){
MyThread thread = new MyThread (); // instantiate a runnable object
Thread thread1 = new Thread (thread); // pass the runnable object through Thread
Thread1.start ();
}
}
(2) Resource Sharing is sometimes required when Runnable is used for multithreading.
When a task is assigned to multiple users, resource sharing is required.
Synchronized (this ){
Synchronous Code Block
}
Let's take a ticket purchase example.
Define a ThreadTicket class
Package MyThread; public class ThreadTicket {public static void main (String [] args) {MyThread myThread1 = new MyThread (); Thread t1 = new Thread (myThread1 ); // one window Thread t2 = new Thread (myThread1); // two windows Thread t3 = new Thread (myThread1); // three windows t1.start (); t2.start (); t3.start ();}}
MyThread Interface Class
Package MyThread; public class MyThread implements Runnable {private int ticket = 10; @ Overridepublic void run () {// synchronized (this) // {for (int I = 0; I <10; I ++) {try {Thread. sleep (500);} catch (InterruptedException e) {// catch Block e automatically generated by TODO. printStackTrace ();} if (ticket> 0) System. out. println ("ticket:" + ticket --);}//}}}
From the MyThread class, we can conclude that the total number of tickets purchased at this time is 10 tickets, which are bought in three windows. At this time, we need three windows to share the ticket source. When there is no ticket, no ticket is sold.
If the synchronized keyword is not added, the result is
It can be seen that the result is disorganized, and resource sharing is not achieved at all.
In this case, we should use synchronized (this)
{
// Code
}
Synchronize code blocks for Resource Sharing
Is to remove the synchronized part of MyThread, the result is
Resource Sharing is achieved successfully.
A major advantage of Runnable is resource sharing.