当时写的时候没写出来, 结束了改了改代码发现实现了,思路没错,写的地方写错了. 补充下线程交替输出的代码: static class Resource { int num; public Resource(int num) { this.num = num; } public synchronized void increment() { num++; if (num == 11) { num = 1; } notify(); System.out.println(num + ": " +Thread.currentThread().getName()); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { Resource resource = new Resource(0); new Thread(() -> { while (true) { resource.increment(); } }, "t1").start(); new Thread(() -> { while (true) { resource.increment(); } }, "t2").start(); }
点赞 评论

相关推荐

牛客网
牛客企业服务