8-2多线程----线程的创建和使用(2)创建Thread类的匿名子类的方式

线程的创建和使用(2)创建Thread类的匿名子类的方式

代码:

package exer1;

public class ThreadDemo {
    public static void main(String[] args) {
//        MyThread1 m1 = new MyThread1();
//        MyThread2 m2 = new MyThread2();
//
//        m1.start();
//        m2.start();

        //创建Thread类的匿名子类的方式
        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    if (i % 2 == 0) {
                        System.out.println(Thread.currentThread().getName() + ":" + i);
                    }
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    if (i % 2 != 0) {
                        System.out.println(Thread.currentThread().getName() + ":" + i);
                    }
                }
            }
        }.start();
    }
}

class MyThread1 extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}
 
class MyThread2 extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 != 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

输出:

Thread-0:0
Thread-0:2
Thread-0:4
Thread-0:6
Thread-0:8
Thread-0:10
Thread-0:12
Thread-0:14
Thread-0:16
Thread-0:18
Thread-0:20
Thread-0:22
Thread-0:24
Thread-0:26
Thread-0:28
Thread-1:1
Thread-1:3
Thread-0:30
Thread-1:5
Thread-0:32
Thread-1:7
Thread-1:9
Thread-1:11
Thread-1:13
Thread-1:15
Thread-1:17
Thread-0:34
Thread-0:36
Thread-0:38
Thread-0:40
Thread-0:42
Thread-0:44
Thread-1:19
Thread-1:21
Thread-1:23
Thread-0:46
Thread-0:48
Thread-0:50
Thread-0:52
Thread-0:54
Thread-0:56
Thread-0:58
Thread-0:60
Thread-0:62
Thread-0:64
Thread-1:25
Thread-1:27
Thread-1:29
Thread-1:31
Thread-0:66
Thread-1:33
Thread-0:68
Thread-1:35
Thread-0:70
Thread-1:37
Thread-1:39
Thread-1:41
Thread-1:43
Thread-1:45
Thread-1:47
Thread-1:49
Thread-1:51
Thread-0:72
Thread-0:74
Thread-1:53
Thread-0:76
Thread-0:78
Thread-0:80
Thread-0:82
Thread-0:84
Thread-0:86
Thread-0:88
Thread-0:90
Thread-0:92
Thread-0:94
Thread-0:96
Thread-0:98
Thread-1:55
Thread-1:57
Thread-1:59
Thread-1:61
Thread-1:63
Thread-1:65
Thread-1:67
Thread-1:69
Thread-1:71
Thread-1:73
Thread-1:75
Thread-1:77
Thread-1:79
Thread-1:81
Thread-1:83
Thread-1:85
Thread-1:87
Thread-1:89
Thread-1:91
Thread-1:93
Thread-1:95
Thread-1:97
Thread-1:99
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YY鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值