Java程序示例多线程的使用方式
下面是一个Java程序示例,演示了多线程的使用方式:
public class MultiThreadExample {
public static void main(String[] args) {
// 创建并启动两个线程
Thread thread1 = new MyThread("Thread 1");
Thread thread2 = new MyThread("Thread 2");
thread1.start();
thread2.start();
// 创建并启动一个实现Runnable接口的线程
Runnable runnable = new MyRunnable();
Thread thread3 = new Thread(runnable);
thread3.start();
}
}
class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + " is running");
try {
Thread.sleep(1000); // 让线程休眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Runnable thread is running");
try {
Thread.sleep(1000); // 让线程休眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
上述示例中,我们创建了三个线程。两个线程是通过继承Thread类来创建的,一个线程是通过实现Runnable接口来创建的。
线程1和线程2是通过继承Thread类来创建的,它们分别输出自己的名称,并休眠1秒钟。线程3是通过实现Runnable接口来创建的,它输出固定的文本,并休眠1秒钟。
在main方法中,我们分别创建了线程1、线程2和线程3的实例,并调用start()方法来启动它们。start()方法会自动调用线程的run()方法,从而开始执行线程的任务。
运行上述示例,你将看到三个线程同时执行,每个线程输出自己的名称或者固定的文本,并每隔1秒钟休眠一次
原文地址: https://www.cveoy.top/t/topic/h95l 著作权归作者所有。请勿转载和采集!