Only single inheritance is allowed in Java, but allows multiple interfaces to be implemented, so the second method is more flexible.
Copy Code code as follows:
/**
* Run the thread that inherits the Java.lang.Thread class definition
*/
public void Startone () {
Create an instance
Onethread onethread = new Onethread ();
Start Thread Threada
Onethread.startthreada ();
try {
Set thread sleep 1 seconds
Thread.Sleep (1000);
catch (Interruptedexception e) {
E.printstacktrace ();
}
Stop the thread, why not use the Stop () method here, because the method is deprecated, but can be used in a deadlock.
Onethread.stopthreada ();
}
Copy Code code as follows:
/**
* Run the thread that implements the Runnable interface definition
*/
public void Starttwo () {
Create an instance
Runnable Runnable = new Twothread ();
Putting an instance into a thread
Thread threadb = new Thread (runnable);
Start thread
Threadb.start ();
}
Copy Code code as follows:
Inheritance thread class defines 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 thread class definition thread body ..." + i++);
Thread.Sleep (200);
}
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
public void Startthreada () {
System.out.println ("Start inheritance thread class definition threads");
This.start ();
}
public void Stopthreada () {
System.out.println ("Close Inheritance thread class definition threads");
This.running = false;
}
}
Copy Code code as follows:
Implementing the Runnable Interface definition thread
Class Twothread implements Runnable {
Private Date rundate;
public void Run () {
System.out.println ("Implement runnable interface definition thread body ...");
This.rundate = new Date ();
SYSTEM.OUT.PRINTLN ("Thread start time ..." + rundate);
}
Copy Code code as follows:
public static void Main (string[] args) {
Instantiating an Object
Threadstartandstop threadstartandstop = new Threadstartandstop ();
Threadstartandstop.startone ();
Threadstartandstop.starttwo ();
}
To start the inheritance thread class definition thread
Inherit thread class definition thread body ... 0
Inherit thread class definition thread body ... 1
Inherit thread class definition thread body ... 2
Inherit thread class definition thread body ... 3
Inherit thread class definition thread body ... 4
Close inherited thread class definition thread
Implement the Runnable interface to define the thread body ...
Thread Start time ... Fri Mar 12:56:57 CST 2013