Write a program to simulate four ticket window programs that sell 100 train tickets together.
1: implement it by inheriting the Thread class ().
2: implement the Runnable interface ().
Method 1
Package com. ljq. test;
/**
* Use the Thread class to simulate four ticket window programs that sell 100 ticket tickets together
*
* No data is shared. Each thread sells 100 train tickets each time.
*
* @ Author jiqinlin
*
*/
Public class ThreadTest {
Public static void main (String [] args ){
New MyThread (). start ();
New MyThread (). start ();
New MyThread (). start ();
New MyThread (). start ();
}
Public static class MyThread extends Thread {
// Ticket quantity
Private int tickets = 100;
@ Override
Public void run (){
While (tickets> 0 ){
System. out. println (this. getName () + "sell train tickets ");
}
}
}
}
Method 2
Package com. ljq. test;
/**
* Use the Runnable interface to simulate four ticket window programs that sell 100 ticket tickets together
*
* Data Sharing: Four threads sell the 100 train tickets together
* @ Author jiqinlin
*
*/
Public class RunnableTest {
Public static void main (String [] args ){
Runnable runnable = new MyThread ();
New Thread (runnable). start ();
New Thread (runnable). start ();
New Thread (runnable). start ();
New Thread (runnable). start ();
}
Public static class MyThread implements Runnable {
// Ticket quantity
Private int tickets = 100;
Public void run (){
While (tickets> 0 ){
System. out. println (Thread. currentThread (). getName () + "sell train tickets ");
}
}
}
}
Comparison of the two thread creation methods
Use the Runnable interface
In practice, almost all multi-threaded applications use Runnable.
Runnable is suitable for multiple threads with the same program code to process the same resource. Effectively separating virtual CPU (thread) from program code and data reflects the object-oriented design idea.
Avoid the limitations caused by Java's single inheritance feature. That is, if the newly created class needs to inherit other classes, Because JAVA does not support multi-inheritance, it can only implement the java. lang. Runnable interface.
It is conducive to program robustness. The code can be shared by multiple threads, and the code and data are independent.
Inherit Thread class
You cannot inherit from other classes.
It is easy to write and can directly manipulate threads without using Thread. currentThread ().
Query the API to obtain the description of the currentThread method.