线程学习练习题

时间:2023-02-23 13:46:58

实现一个Runnable类,在run()内部打印一个消息,然后调用yield(). 重复这个操作3次,然后从run()中返回。在构造器中放置一条启动消息,并且放置一条在任务终止时的关闭消息。使用线程创建大量的这种任务并驱动他们


package com.nstc.test4;
 
public class RunnableDemo implements Runnable {
    private String startMsg;
    private String endMsg;
 
    public RunnableDemo(String startMsg, String endMsg) {
        super();
        this.startMsg = startMsg;
        this.endMsg = endMsg;
    }
 
    @Override
    public void run() {
        System.out.println(this+startMsg+" start");
        for (int i = 0; i < 3; i++) {
            System.out.println("run " + i );
            Thread.yield();
        }
        System.out.println(this+endMsg+" end");
    }
    public static void main(String[] args) {
        RunnableDemo demo=new RunnableDemo("a","b");
        Thread thread1=new Thread(demo);
        thread1.start();
        Thread thread2=new Thread(demo);
        thread2.start();
        Thread thread3=new Thread(demo);
        thread3.start();