java两个线程分别交替打印a和b打印100次
下面是一个示例代码,使用两个线程分别交替打印a和b,打印100次。
public class AlternatePrinting {
private static Object lock = new Object();
private static int count = 0;
public static void main(String[] args) {
Thread threadA = new Thread(new PrintThread("a", 0));
Thread threadB = new Thread(new PrintThread("b", 1));
threadA.start();
threadB.start();
}
static class PrintThread implements Runnable {
private String message;
private int threadId;
public PrintThread(String message, int threadId) {
this.message = message;
this.threadId = threadId;
}
@Override
public void run() {
while (count < 200) {
synchronized (lock) {
if (count % 2 == threadId) {
System.out.println(message);
count++;
}
}
}
}
}
}
在这个示例中,我们创建了两个线程threadA和threadB,它们分别打印字符"a"和"b"。我们使用一个共享的lock对象来控制两个线程的交替执行。在每次打印之前,线程会检查count的值,并判断是否轮到当前线程打印。如果是,则打印字符并将count递增。通过这种方式,两个线程能够交替打印字符"a"和"b",直到count达到200次为止
原文地址: http://www.cveoy.top/t/topic/h037 著作权归作者所有。请勿转载和采集!