Java创建多线程

来源:互联网 发布:数据库接口 编辑:程序博客网 时间:2024/05/30 22:50

Java创建多线程有两种方法:

1继承Thread类

先创建一个类thread1继承thread类,并重写run方法;

然后实例化一个thread1的对象t1,调用start方法。

class Thread1 extends Thread{
public void run(){
System.out.println("----");
}

}
public class Test1 {
public static void main(String[] args) {
Thread1 t1 = new Thread1();
t1.start();
System.out.println("main----");
}
}

2实现runnable接口(推荐使用,因为Java只能实现单继承)

编写一个类thread2实现runnable接口,生成一个thread2的对象t2;然后编写一个thread类并生成一个对象t;最后将t2作为参数传递给thread对象t并执行start方法。

class Thread2 implements Runnable{
public void run() {
System.out.println("---");
}
}
public class Test2 {
public static void main(String[] args) {
Thread2 t2 = new Thread2();
Thread t = new Thread(t2);
t.start();
System.out.println("main---");
}
}

0 0
原创粉丝点击