附加内容:
线程间的同步与通信
问题: 线程在访问共享数据时可能会互相干扰。
解决方案:
同步方法
synchronized void synchronizedmethod() { // código sincronizado }
同步块:
synchronized (this) { // código sincronizado }
沟通示例:
线程之间使用wait()、notify()和notifyall()进行通信:
class SharedResource { private boolean flag = false; synchronized void produce() { while (flag) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Producing..."); flag = true; notify(); } synchronized void consume() { while (!flag) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Consuming..."); flag = false; notify(); } } public class ThreadCommunication { public static void main(String[] args) { SharedResource resource = new SharedResource(); Thread producer = new Thread(resource::produce); Thread consumer = new Thread(resource::consume); producer.start(); consumer.start(); } }
结论