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