JAVA 代码模拟多线程
以下是一个简单的Java代码示例,用于模拟多线程:
public class MultiThreadDemo {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable("Thread 1"));
Thread thread2 = new Thread(new MyRunnable("Thread 2"));
Thread thread3 = new Thread(new MyRunnable("Thread 3"));
thread1.start();
thread2.start();
thread3.start();
}
static class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + ": " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
上面的代码创建了三个线程,每个线程都执行相同的任务。任务是打印线程名称和计数器的值,并在每次打印后等待1秒钟。运行此代码将会看到三个线程同时执行任务,打印出不同的计数器值。
请注意,这只是一个简单的示例,用于演示多线程的概念。在实际应用中,需要根据具体需求设计合适的多线程方案,并注意线程安全性和同步问题

原文地址: http://www.cveoy.top/t/topic/ibzR 著作权归作者所有。请勿转载和采集!