e.printStackTrace()与System.out.print输出顺序混乱的问题

如下图,如果在catch语句中把e.printStackTrace放在第一句,异常的输出也是在第一句,和我们想法一样
在这里插入图片描述


but 如果将e.printStackTrace放在第二句,在输出面板上的异常输出并不是我们想要的在第二句执行,而是在最后一句输出(但此时如果以debug的形式进行测试,异常输出是在第二位的),如下图:
在这里插入图片描述
在这里插入图片描述


这是因为我们正常使用 printStackTrace()的时候默认是输出到System.err中去的,而普通的输出都是放入System.out,这两者都是对上层封装的输出流,在默认情况下两者是指向Console的文本流。所以两者可能会出现同步问题。


解决办法是在e.printStackTrace()以System.out的形式输出,如下图,顺序正常了
在这里插入图片描述

package 操作系统实验二; import java.util.concurrent.*; class PrintTask implements Runnable { private char ch; private Semaphore currentSemaphore; private Semaphore nextSemaphore; public PrintTask(char ch, Semaphore currentSemaphore, Semaphore nextSemaphore) { this.ch = ch; this.currentSemaphore = currentSemaphore; this.nextSemaphore = nextSemaphore; } public void run() { try { for (int i = 0; i < 3; i++) { currentSemaphore.acquire(); System.out.print(ch); nextSemaphore.release(); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class Main { public static void main(String[] args) { Semaphore semaphoreA = new Semaphore(1); Semaphore semaphoreB = new Semaphore(0); PrintTask printA = new PrintTask('A', semaphoreA, semaphoreB); PrintTask printB = new PrintTask('B', semaphoreB, semaphoreA); ExecutorService executorService = Executors.newFixedThreadPool(2); // 顺序1:AAAB executorService.execute(printA); executorService.execute(printA); executorService.execute(printA); executorService.execute(printB); // 顺序2:BBAA //executorService.execute(printB); //executorService.execute(printB); //executorService.execute(printA); //executorService.execute(printA); // 顺序3:AABA //executorService.execute(printA); //executorService.execute(printA); //executorService.execute(printB); //executorService.execute(printA); // 顺序4:ABAA //executorService.execute(printA); //executorService.execute(printB); //executorService.execute(printA); //executorService.execute(printA); executorService.shutdown(); } }
06-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值