首页 > 编程语言 > 详细

java线程

时间:2019-04-24 14:07:43      阅读:122      评论:0      收藏:0      [点我收藏+]

线程的实现:

1.继承Thread 类,重写run函数

技术分享图片
package demo2;

public class Demo1 {
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.start();
    }

}

class Cat extends Thread {
    int times = 0;

    // 重写run函数
    public void run() {
        while (true) {
            // 每一秒打印一次
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                // TODO: handle exception
            }
            System.out.println("hello,world");
            times++;
            if (times == 10)
                break;
        }
    }
}
View Code

 

2.实现Runable接口,重写run函数 

技术分享图片
package demo2;

public class Demo1 {
    public static void main(String[] args) {
        Cat cat = new Cat();
        Thread t = new Thread(cat);
        t.start();
    }

}

class Cat implements Runnable {

    int times = 0;

    // 重写run函数
    public void run() {
        while (true) {
            // 每一秒打印一次
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                // TODO: handle exception
            }
            System.out.println("hello,world");
            times++;
            if (times == 10)
                break;
        }
    }
}
View Code

 

3.多线程运作

 

java线程

原文:https://www.cnblogs.com/helloworld2019/p/10761943.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!