关乎Java多线程+Runnable和Thread…
来源:互联网 发布:无懈可击知乎 编辑:程序博客网 时间:2024/05/18 03:45
两种方法
一种是继承自Thread类.Thread 类是一个具体的类,即不是抽象类,该类封装了线程的行为.要创建一个线程,程序员必须创建一个从 Thread 类导出的新类.程序员通过覆盖 Thread 的 run() 函数来完成有用的工作.用户并不直接调用此函数;而是通过调用 Thread 的 start() 函数,该函数再调用 run().
例如:
public class Test extends Thread{
public Test(){
}
public static void main(String args[]){
Test t1 = new Test();
Test t2 = new Test();
t1.start();
t2.start();
}
public void run(){
//do thread's things
}
}
--------------------------------------------------------------------------------
另一种是实现Runnable接口,此接口只有一个函数,run(),此函数必须由实现了此接口的类实现.
例如:
public class Test implements Runnable{
Thread thread1;
Thread thread2;
public Test(){
thread1 = new Thread(this,"1");
thread2 = new Thread(this,"2");
}
public static void main(String args[]){
Test t = new Test();
t.startThreads();
}
public void run(){