java开启五个线程分别运行不同的方法
时间: 2024-03-01 19:50:34 浏览: 18
在Java中,可以通过继承Thread类或实现Runnable接口来创建线程,并在run方法中实现线程的运行代码。以下是一个示例代码:
```java
public class MyThread1 extends Thread {
public void run() {
System.out.println("This is thread 1");
}
}
public class MyThread2 extends Thread {
public void run() {
System.out.println("This is thread 2");
}
}
public class MyThread3 extends Thread {
public void run() {
System.out.println("This is thread 3");
}
}
public class MyThread4 extends Thread {
public void run() {
System.out.println("This is thread 4");
}
}
public class MyThread5 extends Thread {
public void run() {
System.out.println("This is thread 5");
}
}
public class Main {
public static void main(String[] args) {
// 创建多个线程并启动
MyThread1 thread1 = new MyThread1();
MyThread2 thread2 = new MyThread2();
MyThread3 thread3 = new MyThread3();
MyThread4 thread4 = new MyThread4();
MyThread5 thread5 = new MyThread5();
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
```
在这个例子中,定义了5个不同的线程类,分别继承Thread类,并重写了run方法实现不同的线程运行代码。在创建线程对象时,分别创建了5个不同的线程对象,调用start方法启动线程。
需要注意的是,在开启多个线程时,尽量避免对共享资源的并发访问,以避免出现线程安全问题。可以使用synchronized等机制来保证线程安全性。