首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Thread循环-扩展Thread类Java

Thread循环-扩展Thread类Java
EN

Stack Overflow用户
提问于 2019-06-27 08:57:11
回答 1查看 116关注 0票数 0

我需要编写一个扩展Thread类的应用程序。我的类在实例化时接受一个整数(即100)。(MyThread myt = new MyThread(100); )此整数将是该类循环和打印消息的次数。消息应为“线程正在运行…”100“。100将是我传入构造函数的任何数字。如果这个数字是150,那么输出应该是“线程正在运行…100“。我应该使用main方法来测试这个类。在主要我将启动两个线程,一个线程与150和一个线程与200。对于这段代码,我不需要使用sleep()方法。

我已经写了一段代码,但是我很困惑。我的消息应该打印100次吗?我不确定我的代码是否满足所有必备条件。我还应该实现此代码,将此类更改为使用Runnable接口而不是Thread类

代码语言:javascript
复制
public class MyThread extends Thread {

    private int numtimes;

    public MyThread(int numtimes) {
        this.numbtimes = numbtimes;

    }

    public void run() {

        for (int i = 0; i < numbtimes; i++) {
            System.out.println("Thread Running..." + numbtimes);

        }
    }

    public static void main(String[] args) {

        MyThread mytr1 = new MyThread(150);
        mytr1.start();

        MyThread mytr2 = new MyThread(200);
        mytr2.start();
    }

}

这是被问到的问题吗?你会如何使用Runnable接口?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-27 09:45:25

两种你可以使用的方式。实际上是同一种。但我更喜欢lambda

代码语言:javascript
复制
public class StackOverFlowDemo {

/**
 * one
 * */
public static class MyRun implements Runnable {
    private int numtimes;

    public MyRun(int numtimes) {
        this.numtimes = numtimes;
    }

    @Override
    public void run() {
        for (int i = 0; i < numtimes; i++) {
            System.out.println(String.format("Thread(%s) Running... numtimes(%d), current count (%d) ",
                    Thread.currentThread().getName(),
                    numtimes, i));
        }
    }
}

/**
 * another way
 * */
public static void print(int numtimes) {
    for (int i = 0; i < numtimes; i++) {
        System.out.println(String.format("Thread(%s) Running... numtimes(%d), current count (%d) ",
                Thread.currentThread().getName(),
                numtimes, i));
    }
}

public static void main(String[] args) {
    /**
     * one
     * */
    Thread t1 = new Thread(new MyRun(150), "thread 1");
    Thread t2 = new Thread(new MyRun(200), "thread 2");
    t1.start();
    t2.start();

    /**
     * another way
     * */
    new Thread(() -> StackOverFlowDemo.print(150), "t1").start();
    new Thread(() -> StackOverFlowDemo.print(200), "t2").start();
}

}

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56782632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档