3. Runnable is more flexible than Thread
public class DemoClass extends Thread(){
//class definition
}
- Override "public void run(){}" method
@Override
public void run(){
//function definition
}
DemoClass d1 = new DemoClass();
d1.start();
DemoClass d2 = new DemoClass();
d2.start();
public class MyThread2 extends Thread{
/* Since java only support extends only 1 class,
* MyThread2 can not act as other class's subclass*/
String name;
int time_pause;
MyThread2(String name, int time_pause){
this.name = name;
this.time_pause = time_pause;
}
/*
* override run() from super class
*/
@Override
public void run(){
while(true){
System.out.println(name);
try {
Thread.sleep(time_pause);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
/*directly use the Class "MyThread2" we defined before*/
MyThread2 mt1 = new MyThread2("fast",1000);
mt1.start();
MyThread2 mt2 = new MyThread2("slow", 3000);
mt2.start();
}
}
public Demo implements Runnable {}
@Override
public void run() {}
public class Demo implements Runnable...
Thread t = new Thread(new Demo());
t.start();
Demo m = new Demo();
Thread t2 = new Thread(m);
t2.start();
public class MyThread implements Runnable{
/*
* Implements Runnable is more preferred.
* A class can implement multiple interfaces,
* but can only extends single calss*/
int pause_time;
String name;
MyThread(int pause_time, String name){
this.pause_time=pause_time;
this.name = name;
}
@Override
public void run() {
while(true){
System.out.println(name+":"+new Date(System.currentTimeMillis()));
try {
Thread.sleep(pause_time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
/*
* can not create the class directly,
* initialize the class using Thread class*/
Thread t1 = new Thread(new MyThread(1000, "fast"));
t1.start();
Thread t2 = new Thread(new MyThread(3000, "slow"));
t2.start();
}
}
public class Demo1 extends Thread {} //extends singel class
public class Demo2 implements Runnable, OtherInterface {} //implements multiple interfaces
...Demo1 extends Thread...
Demo1 d1 = new Demo1();
d1.start();
Demo1 d2 = new Demo1();
d2.start();
//d1 d2 are seperate threads, share no data.
Demo2 d = new Demo2();
Thread d1 = new Thread(d);
d1.start();
Thread d2 = new Thread(d);
d2.start();
// d1 & d2 using same d, they share d.
blog.csdn.net/wwww1988600/article/details/7309070