Java 多线程编程示例:实现左手右手交替打印
以下是使用Java实现的简单多线程程序应用,实现Lefthand类打印10次'我是左手',Righthand类打印5次'我是右手'的功能:
class Lefthand implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println('我是左手');
}
}
}
class Righthand implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println('我是右手');
}
}
}
public class Main {
public static void main(String[] args) {
Lefthand lefthand = new Lefthand();
Righthand righthand = new Righthand();
Thread thread1 = new Thread(lefthand);
Thread thread2 = new Thread(righthand);
thread1.start();
thread2.start();
}
}
在程序中,我们定义了Lefthand类和Righthand类,它们实现了Runnable接口,并重写了run方法来执行相应的打印操作。在Main类中,我们创建了一个Lefthand对象和一个Righthand对象,并使用Thread类将它们包装成线程对象。然后,使用start方法启动两个线程。
运行程序时,Lefthand类将打印10次'我是左手',而Righthand类将打印5次'我是右手'。由于多线程的执行顺序是不确定的,因此打印结果可能会有所不同。
原文地址: http://www.cveoy.top/t/topic/z8B 著作权归作者所有。请勿转载和采集!