Additional content:
Synchronization and Communication between Threads
Issue: Threads can interfere with each other when accessing shared data.
Solution:
Synchronized methods
synchronized void synchronizedMethod() { // Código sincronizado }
Synchronized blocks:
synchronized (this) { // Código sincronizado }
Example of Communication:
Communication between threads using wait(), notify() and 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(); } }
Conclusion
The above is the detailed content of Synchronization and Communication between Threads. For more information, please follow other related articles on the PHP Chinese website!