我需要编写一个扩展Thread类的应用程序。我的类在实例化时接受一个整数(即100)。(MyThread myt = new MyThread(100); )此整数将是该类循环和打印消息的次数。消息应为“线程正在运行…”100“。100将是我传入构造函数的任何数字。如果这个数字是150,那么输出应该是“线程正在运行…100“。我应该使用main方法来测试这个类。在主要我将启动两个线程,一个线程与150和一个线程与200。对于这段代码,我不需要使用sleep()方法。
我已经写了一段代码,但是我很困惑。我的消息应该打印100次吗?我不确定我的代码是否满足所有必备条件。我还应该实现此代码,将此类更改为使用Runnable接口而不是Thread类
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接口?
发布于 2019-06-27 09:45:25
两种你可以使用的方式。实际上是同一种。但我更喜欢lambda
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();
}}
https://stackoverflow.com/questions/56782632
复制相似问题