https://stackabuse.com/synchronized-keyword-in-java/#:~:text=To%20avoid%20such%20issues%2C%20Java,the%20resource%20to%20become%20free.
public class NonSynchronizedMethod { public void printNumbers() { System.out.println("Starting to print Numbers for " + Thread.currentThread().getName()); for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + " " + i); } System.out.println("Completed printing Numbers for " + Thread.currentThread().getName()); } }
class ThreadOne extends Thread { NonSynchronizedMethod nonSynchronizedMethod; public ThreadOne(NonSynchronizedMethod nonSynchronizedMethod) { this.nonSynchronizedMethod = nonSynchronizedMethod; } public void run() { nonSynchronizedMethod.printNumbers(); } } class ThreadTwo extends Thread { NonSynchronizedMethod nonSynchronizedMethod; public ThreadTwo(NonSynchronizedMethod nonSynchronizedMethod) { this.nonSynchronizedMethod = nonSynchronizedMethod; } public void run() { nonSynchronizedMethod.printNumbers(); } }
public class TestSynchronization { public static void main(String[] args) { NonSynchronizedMethod nonSynchronizedMethod = new NonSynchronizedMethod(); ThreadOne threadOne = new ThreadOne(nonSynchronizedMethod); threadOne.setName("ThreadOne"); ThreadTwo threadTwo = new ThreadTwo(nonSynchronizedMethod); threadTwo.setName("ThreadTwo"); threadOne.start(); threadTwo.start(); } }
public synchronized void printNumbers() { System.out.println("Starting to print Numbers for " + Thread.currentThread().getName()); for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + " " + i); } System.out.println("Completed printing Numbers for " + Thread.currentThread().getName()); }
No comments:
Post a Comment