java两个线程分别交替打印a和b打印100次 考虑性能问题
在考虑性能问题时,可以使用wait()和notify()方法来实现线程的交替打印。下面是一个示例代码:
public class PrintAB {
private static final Object lock = new Object();
private static int count = 0;
public static void main(String[] args) {
Thread threadA = new Thread(new PrintA());
Thread threadB = new Thread(new PrintB());
threadA.start();
threadB.start();
}
static class PrintA implements Runnable {
@Override
public void run() {
while (count < 100) {
synchronized (lock) {
while (count % 2 == 1) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("a");
count++;
lock.notify();
}
}
}
}
static class PrintB implements Runnable {
@Override
public void run() {
while (count < 100) {
synchronized (lock) {
while (count % 2 == 0) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("b");
count++;
lock.notify();
}
}
}
}
}
在上述代码中,使用了一个共享的锁对象lock和一个计数器count来控制线程的交替打印。PrintA线程负责打印"a",PrintB线程负责打印"b"。每个线程在打印完字符后,都会调用lock.notify()方法通知另一个线程继续执行,并调用lock.wait()方法自己进入等待状态,直到被另一个线程唤醒。
这种方式可以避免线程的忙等待,提高了性能
原文地址: http://www.cveoy.top/t/topic/h04g 著作权归作者所有。请勿转载和采集!