欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

建立线程

程序员文章站 2022-07-12 20:30:18
...
建立线程:

继承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()+"结束了");
    }
}
相关标签: thread