The two implementation methods of the thread can achieve resource sharing by implementing the thread method of the runnable interface, but not by inheriting the thread. Why? Let's take a look at the following two pieces of code:
Thread implementation through thread:
// Resources cannot be shared using threads. <br/> class mythread extends thread <br/>{< br/> private int ticket = 5; <br/> private string name; <br/> Public mythread (string name) {<br/> This. name = Name; <br/>}< br/> Public void run () {<br/> for (INT I = 0; I <10; I ++) {<br/> If (ticket> 5) {<br/> system. out. println ("Thread" + name + "ticket selling" + I ); <br/>}</P> <p >}< br/>}</P> <p> public class threaddemo02 <br/> {<br /> Public static void main (string ARGs []) {<br/> mythread A = new mythread ("A"); <br/> mythread B = new mythread ("B"); <br/>. start (); <br/> B. start (); <br/>}< br/>}
Implemented through runnable:
// Use runnable to implement threads for Resource Sharing <br/> class mythread implements runnable <br/>{< br/> private int ticket = 5; <br/> private string name; <br/> Public mythread (string name) {<br/> This. name = Name; <br/>}< br/> Public void run () {<br/> for (INT I = 1; I <= 10; I ++) {<br/> If (ticket> 0) {<br/> system. out. println ("Thread" + name + "ticket selling" + (ticket --)); <br/>}< br/> public class runnabledemo02 <br/>{< br/> Public static void main (string ARGs []) {<br/> mythread A = new mythread ("A"); // instantiate the task to be executed by the thread <br/> thread TA = new thread (); // two thread objects in the instance, actually passing a task <br/> thread TB = new thread (a); // because the two threads execute a task, therefore, resources are shared. <br/> Ta. start (); <br/> TB. start (); <br/>}< br/>}
Explanation:
Because a thread can only be started once. When a thread is used to implement a thread, the thread and the task to be executed by the thread are bundled together. In this way, only one thread can be started for a task, and the tasks executed by different threads are different. Therefore, it is not necessary to allow two threads to share resources of each other's tasks.
A task can start multiple threads and implement the threads in runnable mode. In fact, a thread is opened up to pass the task in, and thus the thread is executed. Multiple thread objects can be instantiated, and the same task can be passed in, that is, a task can start multiple threads to execute it. These threads execute the same task, so their resources are shared.
The two different thread implementation methods determine whether they can share resources.