Skip to content

Instantly share code, notes, and snippets.

@kthakore
Created June 20, 2017 00:43
Show Gist options
  • Save kthakore/6543996a8da18c63f30b3a11529b287f to your computer and use it in GitHub Desktop.
Save kthakore/6543996a8da18c63f30b3a11529b287f to your computer and use it in GitHub Desktop.
Threads in Java with Syncronized!
package com.java.oop.threads;
import java.lang.Runnable;
import java.lang.Thread;
/**
* Created by kthakore on 2017-06-19.
*/
public class Run implements Runnable {
SyncInteger count;
Run(SyncInteger count) {
this.count = count;
}
public void run() {
System.out.println("RunnerThread starting.");
try {
while (count.isLessThan(5)) {
Thread.sleep(250);
count.add(1);
}
} catch (InterruptedException exc) {
exc.printStackTrace();
}
}
public static class ListenerThread extends Thread {
SyncInteger count;
ListenerThread(SyncInteger count) {
this.count = count;
}
@Override
public void run() {
System.out.println("ListenerThread starting.");
try {
while (count.isLessThan(5)) {
Thread.sleep(200);
System.out.printf("LISTENING: %d\n", count.getValue());
}
} catch (InterruptedException exc) {
exc.printStackTrace();
}
}
}
public static class SyncInteger {
private int val = 0;
SyncInteger(int val ) {
this.setValue(val);
}
public synchronized Integer getValue() {
return val;
}
public synchronized void setValue(int val) {
this.val = val;
}
public synchronized boolean isLessThan(int check) {
return this.val < check;
}
public synchronized void add(int incr) {
this.val = this.val + incr;
}
}
public static void main(String[] args ) {
SyncInteger count = new SyncInteger(0);
Run rt = new Run(count);
ListenerThread lt = new ListenerThread(count);
lt.start();
Thread t = new Thread(rt);
t.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment