java多线程使用代码
时间: 2024-07-17 17:00:39 浏览: 74
java多线程代码
Java多线程是通过Thread类或Runnable接口来创建和管理线程的。以下是一个简单的Java多线程示例,展示了如何通过继承Thread类和实现Runnable接口创建新线程:
**1. 继承Thread类的例子:**
```java
public class MyThread extends Thread {
public void run() {
// 这里是线程执行的任务
System.out.println("Thread " + this.getName() + " is running.");
}
public static void main(String[] args) {
MyThread thread1 = new MyThread();
thread1.setName("Thread 1");
thread1.start();
MyThread thread2 = new MyThread();
thread2.setName("Thread 2");
thread2.start();
}
}
```
**2. 实现Runnable接口的例子:**
```java
public class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("Thread " + name + " is running.");
}
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable("Thread 1"));
thread1.start();
Thread thread2 = new Thread(new MyRunnable("Thread 2"));
thread2.start();
}
}
```
在这些例子中,`run()`方法包含了线程的实际任务,`start()`方法用于启动线程。同时,你可以通过`setName()`方法为线程设置名称,以便于识别。
阅读全文