用java 写一段多线程的程序
时间: 2023-11-17 15:06:12 浏览: 36
以下是一个简单的多线程程序,它启动了两个线程,一个打印数字,另一个打印字母:
```
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new NumberPrinter());
Thread t2 = new Thread(new LetterPrinter());
t1.start();
t2.start();
}
}
class NumberPrinter implements Runnable {
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class LetterPrinter implements Runnable {
public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
在主函数中创建了两个线程对象t1和t2,并通过start()方法启动它们。t1和t2分别执行NumberPrinter和LetterPrinter类中的run()方法,打印数字和字母。每个线程在打印一个字符后,都将休眠1秒钟,以便另一个线程有机会执行。