Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.LinkedList;
- import java.util.Queue;
- import java.util.concurrent.Executor;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.locks.ReentrantLock;
- public class Synchronized {
- static class Holder {
- private int value = 0;
- Object lockA = new Object();
- Object lockB = new Object();
- ReentrantLock rLockA = new ReentrantLock();
- ReentrantLock rLockB = new ReentrantLock();
- synchronized void increment() {
- ++value;
- }
- void doStuff() {
- rLockA.lock();
- // do thing A with mutual exlusion
- rLockA.unlock();
- // do thing C
- synchronized (lockB) {
- // do thing C with mutual exclusion <-- Thread A here
- }
- }
- }
- static class Incrementor extends Thread {
- private final Holder h;
- public Incrementor(Holder h) {
- this.h = h;
- }
- @Override
- public void run() {
- for (int i = 0; i < 50000; i++) {
- h.increment();
- }
- }
- }
- private static class Incrementor1{
- private int counter;
- private synchronized void increment(){
- counter++;
- }
- public void showCounter(){
- System.out.println(counter);
- }
- }
- public static void main(String[] args) throws InterruptedException {
- // ProducerConsumer pd = new ProducerConsumer();
- Incrementor1 i1 = new Incrementor1();
- Thread thread1 = new Thread(new Runnable() {
- @Override
- public void run() {
- for (int i = 0; i < 1000; i++)
- i1.increment();
- }
- });
- Thread thread2 = new Thread(new Runnable() {
- @Override
- public void run() {
- for(int i = 0; i < 1000; i++)
- i1.increment();
- }
- });
- thread1.start();
- thread2.start();
- thread1.join();
- thread2.join();
- i1.showCounter();
- }
- private static class ProducerConsumer{
- private Queue<Integer> queue = new LinkedList<>();
- private final Object lock = new Object();
- int cnt = 0;
- public void produce() throws InterruptedException {
- synchronized (queue) {
- while (true) {
- // synchronized (this) {
- if (queue.size() == 10) {
- queue.wait();
- }
- queue.offer(cnt++);
- queue.notify();
- // }
- }
- }
- }
- public void consume() throws InterruptedException {
- synchronized (queue) {
- while (true) {
- //synchronized (this) {
- if (queue.size() == 0) {
- queue.wait();
- }
- System.out.println(queue.poll());
- System.out.println("size: " + queue.size());
- queue.notify();
- System.out.println("Hello!");
- // }
- Thread.sleep(1000);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement