Only single inheritance is allowed in Java, but multiple interfaces are allowed to be implemented, so the second method is more flexible.
Copy the code code as follows:
/**
* Run threads inherited from the java.lang.Thread class definition
*/
public void startOne() {
//Create instance
OneThread oneThread = new OneThread();
//Start thread ThreadA
oneThread.startThreadA();
try {
//Set the thread to sleep for 1 second
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Stop the thread. Why not use the stop() method here, because this method has been abandoned, but it can be used in deadlocks.
oneThread.stopThreadA();
}
Copy the code code as follows:
/**
* Run threads that implement the Runnable interface definition
*/
public void startTwo() {
//Create instance
Runnable runnable = new TwoThread();
//Put the instance into the thread
Thread threadB = new Thread(runnable);
//Start thread
threadB.start();
}
Copy the code code as follows:
//Inherit the Thread class to define threads
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 to define the thread program body..." + i++);
Thread.sleep(200);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void startThreadA() {
System.out.println("Start the thread defined by inheriting the Thread class");
this.start();
}
public void stopThreadA() {
System.out.println("Close the thread defined by the inherited Thread class");
this.running = false;
}
}
Copy the code code as follows:
// Implement the Runnable interface to define threads
class TwoThread implements Runnable {
private Date runDate;
public void run() {
System.out.println("Implement Runnable interface to define thread program body...");
this.runDate = new Date();
System.out.println("Thread startup time..." + runDate);
}
Copy the code code as follows:
public static void main(String[] args) {
//instantiate object
ThreadStartAndStop threadStartAndStop = new ThreadStartAndStop();
threadStartAndStop.startOne();
threadStartAndStop.startTwo();
}
Start inheriting Thread class definition thread inherit Thread class definition thread program body... 0
Inherit the Thread class to define the thread program body...1
Inherit the Thread class to define the thread program body...2
Inherit the Thread class to define the thread program body...3
Inherit the Thread class to define the thread program body...4
Close the inherited Thread class, define the thread, implement the Runnable interface, and define the thread program body...
Thread start time...Fri Mar 15 12:56:57 CST 2013