java中的线程问题(二)——线程的创建和用法。

**
 * 演示如何通过继承Thread来开发线程
 */
public class Thread01 {
    public static void main(String[] args) {
        //创建一个 Cat对象
        Cat cat=new Cat();
        //启动线程
        cat.start();//.start()会导致run函数运行
    }
}

class Cat extends Thread{
    int times=0;
    //重写run函数
    public void run(){
        while(true){
            //休眠一秒
            //1000表示1000毫秒
            try {
                Thread.sleep(1000);//sleep就会让该线程进入到Blocked阻塞状态,并释放资源。
            } catch (Exception e) {
                e.printStackTrace();
            }
            times++;
            System.out.println("hello,world!"+times);
            if(times==10){
                //退出线程
                break;
            }
        }
    }
}

复制代码

/**
 * 演示如何通过Runnable接口来开发线程
 */
public class Thread02{
    public static void main(String []args){
        Dog dog=new Dog();
        //创建线程
        Thread t=new Thread(dog);
        //启动线程
        t.start();
    }
}
class Dog implements Runnable{//创建Runnable接口
    public void run(){//重写run函数
        int times=0;
        while(true){
            try{
                Thread.sleep(1000);
            }catch (Exception e) {
                e.printStackTrace();
            }
            times++;
            System.out.println("hello,wrold!"+times);
            if(times==10){
                break;
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/u014203489/article/details/81223198