线程是一种可以充分利用cpu资源的技术,在我们日常开发中经常使用,要创建一个线程有两种方式,下面我们来看看,这两种创建方法。
第一种:继承Thread
public class Theardtest extends Thread {
public void run() {
System.out.println("hello");
}
public static void main(String[] args) {
//启动线程的两种方式
Thread thread=new Theardtest();
thread.setName("我是线程1");
thread.start();
}
}
Thread thread=new Theardtest();将类对象传给线程对象。
第二种:继承runnable接口
class Theardtest2 implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("hello,我是线程2");
}
public static void main(String[] args) {
//启动线程的两种方式
Thread thread2=new Thread(new Theardtest2());
thread.setName("我是线程1");
thread2.start();
}
}
Thread thread2=new Thread(new Theardtest2());将继承runnable接口的类的对象传入。