Created
August 27, 2019 23:49
-
-
Save AppLoidx/ac8cc575f9493d66bceb61090b5baab4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class ThreadsExample implements Runnable { | |
| static int counter = 1; // a global counter | |
| static ReentrantLock counterLock = new ReentrantLock(true); // enable fairness policy | |
| static void incrementCounter(){ | |
| // Using ReenterantLock for avoid starvation problem | |
| counterLock.lock(); | |
| // Always good practice to enclose locks in a try-finally block | |
| try{ | |
| System.out.println(Thread.currentThread().getName() + ": " + counter); | |
| counter++; | |
| }finally{ | |
| counterLock.unlock(); | |
| } | |
| } | |
| @Override | |
| public void run() { | |
| while(counter<1000){ | |
| incrementCounter(); | |
| } | |
| } | |
| public static void main(String[] args) { | |
| ThreadsExample te = new ThreadsExample(); | |
| Thread thread1 = new Thread(te); | |
| Thread thread2 = new Thread(te); | |
| thread1.start(); | |
| thread2.start(); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oracle про голодание (starvation):