线程的实现:

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

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。 java线程 随笔 第1张
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函数 

java线程 随笔 第3张
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线程 随笔 第5张
package demo2;

public class Demo2 {
    public static void main(String[] args) {
        Pig pig = new Pig(10);
        Bird bird = new Bird(10);
        Thread t1 = new Thread(pig);
        Thread t2 = new Thread(bird);
        t1.start();
        t2.start();
    }
}

class Bird implements Runnable {
    int n, ret = 0, times = 0;

    public Bird(int times) {
        this.times = times;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                // TODO: handle exception
            }
            System.out.println("飞出来一只鸟");
            ret++;
            if (times == ret)
                break;
        }
    }
}

class Pig implements Runnable {
    int n, ret = 0, times = 0;

    public Pig(int times) {
        this.times = times;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                // TODO: handle exception
            }
            System.out.println("飞出来一只猫");
            ret++;
            if (times == ret)
                break;
        }
    }
}
View Code

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄