21章习题一

21章习题一

package com.company;

/**
 * @Author: gaoyi
 * @Description:
 * @DATE: Created in  2019/3/5.
 * @TIME: 21:27
 */
class Ex1RunnerA implements Runnable {
    public Ex1RunnerA() {
        System.out.println("Constructing Ex1RunnerA");
    }
    public void run() {
        for(int i = 0; i < 3; i++) {
            System.out.println("Hi from Ex1RunnerA");
            //Thread.yield();
        }
        System.out.println("Ex1RunnerA task complete.");
        return;
    }
}

class Ex1RunnerB implements Runnable {
    public Ex1RunnerB() {
        System.out.println("Constructing Ex1RunnerB");
    }
    public void run() {
        for(int i = 0; i < 3; i++) {
            System.out.println("Hi from Ex1RunnerB");
           // Thread.yield();
        }
        System.out.println("Ex1RunnerB task complete.");
        return;
    }
}

class Ex1RunnerC implements Runnable {
    public Ex1RunnerC() {
        System.out.println("Constructing Ex1RunnerC");
    }
    public void run() {
        for(int i = 0; i < 3; i++) {
            System.out.println("Hi from Ex1RunnerC");
           // Thread.yield();
        }
        System.out.println("Ex1RunnerC task complete.");
        return;
    }
}
public class Run1{
    public static void main(String[]args){
        Thread a=new Thread(new Ex1RunnerA());
        Thread b=new Thread(new Ex1RunnerB());
        Thread c=new Thread(new Ex1RunnerC());
        a.start();
        b.start();
        c.start();
    }
}

注释Thread.yield();结果如下

Constructing Ex1RunnerA
Constructing Ex1RunnerB
Constructing Ex1RunnerC
Hi from Ex1RunnerA
Hi from Ex1RunnerA
Hi from Ex1RunnerA
Ex1RunnerA task complete.
Hi from Ex1RunnerB
Hi from Ex1RunnerB
Hi from Ex1RunnerB
Ex1RunnerB task complete.
Hi from Ex1RunnerC
Hi from Ex1RunnerC
Hi from Ex1RunnerC
Ex1RunnerC task complete.

Process finished with exit code 0

不注释如下

Constructing Ex1RunnerA
Constructing Ex1RunnerB
Constructing Ex1RunnerC
Hi from Ex1RunnerA
Hi from Ex1RunnerB
Hi from Ex1RunnerC
Hi from Ex1RunnerA
Hi from Ex1RunnerB
Hi from Ex1RunnerC
Hi from Ex1RunnerA
Hi from Ex1RunnerB
Hi from Ex1RunnerC
Ex1RunnerA task complete.
Ex1RunnerB task complete.
Ex1RunnerC task complete.

Process finished with exit code 0

Thread.yield();告诉 线程调度器 我完成了,请把运行另一个线程的东西

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值