使用Java,分别使用继承Thread 类的方式和实现 Runnable按口的方式创建主线程main 和子线程,修改两个线程的名称分别为含雷和韩梅梅,让其同步循环打印出“李雷线程输出:色和“韩梅梅线程输出:1。循环次数为 30 次。
时间: 2024-10-16 09:07:14 浏览: 18
Java多线程-创建多线程的基本方式一:继承Thread类
在Java中,你可以通过两种方式创建线程:继承Thread类和实现Runnable接口。下面是这两种方法的具体示例,线程名称已修改为"李雷"和"韩梅梅",并且循环打印指定消息30次。
### 继承Thread类
```java
public class ThreadDemo extends Thread {
private String name;
public ThreadDemo(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println(name + "线程输出:" + (i % 2 == 0 ? "色" : "1"));
}
}
public static void main(String[] args) {
// 创建并启动线程
Thread leilei = new ThreadDemo("李雷");
Thread hami = new ThreadDemo("韩梅梅");
// 修改线程名称
leilei.setName("李雷");
hami.setName("韩梅梅");
// 启动线程
leilei.start();
hami.start();
}
}
```
### 实现Runnable接口
```java
public class ThreadDemo implements Runnable {
private String name;
private Thread thread;
public ThreadDemo(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println(name + "线程输出:" + (i % 2 == 0 ? "色" : "1"));
}
}
public void startAsThread() {
thread = new Thread(this);
thread.setName(name); // 设置线程名称
thread.start(); // 启动线程
}
public static void main(String[] args) {
ThreadDemo demo = new ThreadDemo("李雷");
demo.startAsThread();
demo = new ThreadDemo("韩梅梅");
demo.startAsThread();
}
}
```
阅读全文