实现线程的两种方式

1.继承Thread类

/**
 * 创建线程的第一种方式:继承Thread类
 */
public class Demo extends Thread{
    private String name;
    Demo(String name){
        this.name = name;
    }
    public void run(){
        for(int x=0; x<100; x++){
            System.out.println(name + ":" + x);
        }
    }
}
public class ThreadDemo {
    public static void main(String[] args) {
        Demo d1 = new Demo("旺财");
        Demo d2 = new Demo("xiaoqiang");
        d1.start();
        d2.start();
    }
}

2.实现Runnabe接口

/**
 * 创建线程的第二种方式:实现Runnable接口
 */
public class Demo2 implements Runnable{
    private String name;
    Demo2(String name){
        this.name = name;
    }
    public void run(){
        for(int x=0; x<100; x++){
            System.out.println(name + ":" + x);
        }
    }
}
public class ThreadDemo2 {
    public static void main(String[] args) {
        Demo2 d1  = new Demo2("张三");
        Demo2 d2  = new Demo2("zhangsan");
        Thread t1 = new Thread(d1);
        Thread t2 = new Thread(d2);
        t1.start();
        t2.start();
    }
}

 

你可能感兴趣的:(线程,Java)