java代码实现Runnable接口,用Thread方法启动2个线程同时循环输出“线程名-数字”,其中数字从1变化到10.
时间: 2023-11-22 15:53:32 浏览: 83
以下是Java代码实现:
```
public class MyRunnable implements Runnable {
private String threadName;
public MyRunnable(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(threadName + "-" + i);
}
}
}
```
然后在 main 方法中启动两个线程:
```
public static void main(String[] args) {
MyRunnable runnable1 = new MyRunnable("Thread1");
MyRunnable runnable2 = new MyRunnable("Thread2");
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);
thread1.start();
thread2.start();
}
```
这样就可以启动两个线程同时循环输出“线程名-数字”,其中数字从1变化到10。
相关问题
实现一个java程序实现Runnable接口,用Thread方法启动线程的方法实现2个线程同时循环输出“线程名-数字”,其中数字从1变化到10.
下面是一个简单的Java程序,实现了Runnable接口并使用Thread方法启动2个线程,同时循环输出“线程名-数字”,其中数字从1变化到10。
```java
public class ThreadDemo implements Runnable {
private String threadName;
public ThreadDemo(String threadName) {
this.threadName = threadName;
}
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(threadName + "-" + i);
}
}
public static void main(String[] args) {
ThreadDemo td1 = new ThreadDemo("Thread 1");
ThreadDemo td2 = new ThreadDemo("Thread 2");
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
t2.start();
}
}
```
运行程序后,将会看到类似如下的输出:
```
Thread 1-1
Thread 1-2
Thread 1-3
Thread 1-4
Thread 1-5
Thread 1-6
Thread 1-7
Thread 1-8
Thread 1-9
Thread 1-10
Thread 2-1
Thread 2-2
Thread 2-3
Thread 2-4
Thread 2-5
Thread 2-6
Thread 2-7
Thread 2-8
Thread 2-9
Thread 2-10
```
写一个java程序实现Runnable接口,用Thread方法启动线程的方式实现2个线程同时循环输出“线程名-数字”,其中数字从1变化到10.
下面是实现Runnable接口,用Thread方法启动线程的方式实现2个线程同时循环输出“线程名-数字”的Java程序:
```java
public class MyRunnable implements Runnable {
private String name;
private int count;
public MyRunnable(String name) {
this.name = name;
this.count = 1;
}
@Override
public void run() {
while (count <= 10) {
System.out.println(name + "-" + count);
count++;
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable r1 = new MyRunnable("Thread1");
MyRunnable r2 = new MyRunnable("Thread2");
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
```
在这个程序中,我们定义了一个MyRunnable类,实现了Runnable接口,并重写了run()方法。该方法将在线程启动时被调用,并循环输出“线程名-数字”,其中数字从1到10。然后,我们在Main类中创建了两个MyRunnable对象,分别给它们赋予“Thread1”和“Thread2”作为线程名。接下来,我们创建了两个Thread对象,并将它们与MyRunnable对象关联起来。最后,我们分别启动了这两个线程,它们会同时执行并输出“线程名-数字”。
阅读全文