JAVA multi-Thread and Runnable implementation, threadrunnable
Java only supports single inheritance, but multiple interfaces are allowed. Therefore, the second method is more flexible.
Copy codeThe Code is as follows:
/**
* Run the Thread that inherits the definition of the java. lang. Thread class.
*/
Public void startOne (){
// Create an instance
OneThread oneThread = new OneThread ();
// Start the ThreadA thread
OneThread. startThreadA ();
Try {
// Set the thread to sleep for 1 second
Thread. sleep (1000 );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
// Stop the thread. The stop () method is not used here, because the method has been discarded but can be used in deadlocks.
OneThread. stopThreadA ();
}
Copy codeThe Code is as follows:
/**
* Run the thread that implements the Runnable interface definition.
*/
Public void startTwo (){
// Create an instance
Runnable runnable = new TwoThread ();
// Put the instance into the thread
Thread threadB = new Thread (runnable );
// Start the thread
ThreadB. start ();
}
Copy codeThe Code is as follows:
// Inherit the Thread class definition Thread
Class OneThread extends Thread {
Private boolean running = false;
Public void start (){
This. running = true;
Super. start ();
}
Public void run (){
Int I = 0;
Try {
While (running ){
System. out. println ("inherit the Thread class definition Thread program body ......" + I ++ );
Thread. sleep (200 );
}
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
Public void startThreadA (){
System. out. println ("START inheriting Thread class definition Thread ");
This. start ();
}
Public void stopThreadA (){
System. out. println ("disabling the Thread class definition Thread inherited ");
This. running = false;
}
}
Copy codeThe Code is as follows:
// Implement the Runnable interface definition thread
Class TwoThread implements Runnable {
Private Date runDate;
Public void run (){
System. out. println ("Implementing the Runnable interface to define the thread program body ......");
This. runDate = new Date ();
System. out. println ("thread startup time ......" + runDate );
}
Copy codeThe Code is as follows:
Public static void main (String [] args ){
// Instantiate the object
ThreadStartAndStop threadStartAndStop = new ThreadStartAndStop ();
ThreadStartAndStop. startOne ();
ThreadStartAndStop. startTwo ();
}
Start the Thread that inherits the Thread class definition
Inherit the Thread class definition Thread program body... 0
Inherit the Thread class definition Thread program body ...... 1
Inherit the Thread class definition Thread program body ...... 2
Inherit the Thread class definition Thread program body ...... 3
Inherit the Thread class definition Thread program body ...... 4
Disable the Thread that inherits the Thread class definition
Implement the Runnable interface to define the thread program ......
Thread start time... Fri Mar 15 12:56:57 CST 2013