建立线程

建立线程:

继承Thread类,重写run()方法;

实现Runnable接口,实现run()方法;

public class TestThread extends Thread{

    public void run(){
        boolean flag= true;
        System.out.println(getName()+"开始了");
        int count = 0;
        while(flag){
            System.out.println(getName()+"执行了"+(++count));
            if(count %10 == 0){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(getName()+"结束了");
    }

    public static void main(String[] args){
        Thread threadB = new TestThread();
        Thread threadA = new Thread(new TestThread(),"军队");
        Thread threadC = new Thread(new TestThread2(),"将军");
        threadB.setName("农民起义");
        threadA.start();
        threadB.start();
        threadC.start();
    }
}

class TestThread2 implements Runnable{
    @Override
    public void run() {
        boolean flag= true;
        System.out.println(Thread.currentThread().getName()+"开始了");
        int count = 0;
        while(flag){
            System.out.println(Thread.currentThread().getName()+"执行了"+(++count));
            if(count %10 == 0){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(Thread.currentThread().getName()+"结束了");
    }
}

猜你喜欢

转载自se7en1029.iteye.com/blog/2415974