Java Threads - Synchronized(this) - java

Please see the program below
public class TestVolatile implements Runnable {
public static volatile int counter;
public static String lock = "lock";
public static void main(String[] args) {
Thread t1 = new Thread(new TestVolatile(),"Thread-1");
Thread t2 = new Thread(new TestVolatile(),"Thread-2");
t1.start();
t2.start();
}
public void run() {
synchronized(this) {
System.out.println(Thread.currentThread()+"-"+counter);
counter++;
}
}
}
If I run this program multiple times, I get 3 different results.
first is
Thread[Thread-1,5,main]-0
Thread[Thread-2,5,main]-0
second is
Thread[Thread-1,5,main]-0
Thread[Thread-2,5,main]-1
third is
Thread[Thread-1,5,main]-1
Thread[Thread-2,5,main]-0
But if change the lock object from "this" to "lock", I get 2 different results
first is
Thread[Thread-1,5,main]-0
Thread[Thread-2,5,main]-1
second is
Thread[Thread-1,5,main]-1
Thread[Thread-2,5,main]-0
My assumption when writing the program was that in either case the "counter" should never come 0 in both statements.
Can somebody explain?

You create two TestVolatile objects. The "this" keyword refers to the TestVolatile object being run in the thread. Thus you do not synchronize on the same object in the first example.
If you change the code like this, then the first example starts working:
public static void main(String[] args) {
TestVolatile testVolatile = new TestVolatile();
Thread t1 = new Thread(testVolatile,"Thread-1");
Thread t2 = new Thread(testVolatile,"Thread-2");
t1.start();
t2.start();
}

It's probably not what you're looking for, but if you want to avoid the use of synchronized and volatile, you should use an instance of AtomicInteger:
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html
Use the getAndIncrement method to show the same behavior as in your example.
public class TestVolatile implements Runnable {
public static AtomicInteger counter = new AtomicInteger();
public static void main(String[] args) {
Thread t1 = new Thread(new TestVolatile(),"Thread-1");
Thread t2 = new Thread(new TestVolatile(),"Thread-2");
t1.start();
t2.start();
}
public void run() {
System.out.println(Thread.currentThread() + " - " + counter.getAndIncrement());
}
}

Related

Passing command-line arguments to mutliple java threads

I'm trying to create multiple threads in a java program and have them perform arithmetic operations on integers passed as command-line arguments. Obviously neither of the thread classes I'm trying to pass to are in the main method so how can I still access a variable like args[0] from these classes?
public class Mythread {
public static void main(String[] args) {
Runnable r = new multiplication();
Thread t = new Thread(r);
Runnable r2 = new summation();
Thread t2 = new Thread(r2);
t.start();
t2.start();
}
}
class summation implements Runnable{
public void run(){
System.out.print(args[0]);
}
}
class multiplication implements Runnable{
public void run(){
System.out.print(args[1]);
}
}
You should pass in the necessary information in the constructor
class Summation implements Runnable {
private final String info;
public Summation(String info) {
this.info = info;
}
#Override
public void run(){
System.out.print(info);
}
}
Then you can pass in the args values to your threads in main so that you have them in your runnables / threads
public class Mythread {
public static void main(String[] args) {
Runnable r = new multiplication(args[1]);
Thread t = new Thread(r);
Runnable r2 = new summation(args[0]);
Thread t2 = new Thread(r2);
t.start();
t2.start();
}
}

Why is Java synchronized not working as expected?

I'm trying to figure out how synchronized methods work. From my understanding I created two threads T1 and T2 that will call the same method addNew, since the method is synchronized shouldn't it execute all the iterations of the for loop for one thread and then the other? The output keeps varying, sometimes it prints it right, other times it prints values from T1 mixed with T2 values. The code is very simple, can someone point out what am I doing wrong? Thank you.
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new A());
Thread t2 = new Thread(new A());
t1.setName("T1");
t2.setName("T2");
t1.start();
t2.start();
}
}
public class B {
public synchronized void addNew(int i){
Thread t = Thread.currentThread();
for (int j = 0; j < 5; j++) {
System.out.println(t.getName() +"-"+(j+i));
}
}
}
public class A extends Thread {
private B b1 = new B();
#Override
public void run() {
b1.addNew(100);
}
}
Each A instance has its own B instance. The method addNew is an instance method of B. Therefore, the lock acquired implicitly during calls to addNew is the lock on the receiver B instance. Each thread is calling addNew on a different B, and therefore locking on different locks.
If you want all B instances to use a common lock, create a single shared lock, and acquire it in the body of addNew.
Both A objects have their own B object. You need them to share a B so the synchronization can have an effect.
try this :
public class Main {
public static void main(String[] args) {
A a = new A();
Thread t1 = new Thread(a);
Thread t2 = new Thread(a);
t1.setName("T1");
t2.setName("T2");
t1.start();
t2.start();
}
}
class B {
public synchronized void addNew(int i){
Thread t = Thread.currentThread();
for (int j = 0; j < 5; j++) {
System.out.println(t.getName() +"-"+(j+i));
}
}
}
class A extends Thread {
private B b1 = new B();
#Override
public void run() {
b1.addNew(100);
}
}

Java Multithreading - Threadsafe Counter

I'm starting off with a very simple example in multithreading. I'm trying to make a threadsafe counter. I want to create two threads that increment the counter intermittently to reach 1000. Code below:
public class ThreadsExample implements Runnable {
static int counter = 1; // a global counter
public ThreadsExample() {
}
static synchronized void incrementCounter() {
System.out.println(Thread.currentThread().getName() + ": " + counter);
counter++;
}
#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();
}
}
From what I can tell, the while loop right now means that only the first thread has access to the counter until it reaches 1000. Output:
Thread-0: 1
.
.
.
Thread-0: 999
Thread-1: 1000
How do I fix that? How can I get the threads to share the counter?
You could use the AtomicInteger. It is a class that can be incremented atomically, so two seperate threads calling its increment method do not interleave.
public class ThreadsExample implements Runnable {
static AtomicInteger counter = new AtomicInteger(1); // a global counter
public ThreadsExample() {
}
static void incrementCounter() {
System.out.println(Thread.currentThread().getName() + ": " + counter.getAndIncrement());
}
#Override
public void run() {
while(counter.get() < 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();
}
}
Both threads have access to your variable.
The phenomenon you are seeing is called thread starvation. Upon entering the guarded portion of your code (sorry I missed this earlier), other threads will need to block until the thread holding the monitor is done (i.e. when the monitor is released). Whilst one may expect the current thread pass the monitor to the next thread waiting in line, for synchronized blocks, java does not guarantee any fairness or ordering policy to which thread next recieves the monitor. It is entirely possible (and even likely) for a thread that releases and attempts to reacquire the monitor to get hold of it over another thread that has been waiting for a while.
From Oracle:
Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.
Whilst both of your threads are examples of "greedy" threads (since they repeatedly release and reacquire the monitor), thread-0 is technically started first, thus starving thread-1.
The solution is to use a concurrent synchronization method that supports fairness (e.g. ReentrantLock) as shown below:
public class ThreadsExample implements Runnable {
static int counter = 1; // a global counter
static ReentrantLock counterLock = new ReentrantLock(true); // enable fairness policy
static void incrementCounter(){
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();
}
}
note the removal of the synchronized keyword in favor of the ReentrantLock within the method. Such a system, with a fairness policy, allows long waiting threads a chance to execute, removing the starvation.
Well, with your code I don't know how to get "exactly" intermittently, but if you use Thread.yield() after call incrementCounter() you will have a better distribution.
public void run() {
while(counter<1000){
incrementCounter();
Thread.yield();
}
}
Otherwise, to get what you propose, you can create two different thread class (ThreadsExample1 and ThreadsExample2 if you want), and another class to be a shared variable.
public class SharedVariable {
private int value;
private boolean turn; //false = ThreadsExample1 --> true = ThreadsExample2
public SharedVariable (){
this.value = 0;
this.turn = false;
}
public void set (int v){
this.value = v;
}
public int get (){
return this.value;
}
public void inc (){
this.value++;
}
public void shiftTurn(){
if (this.turn){
this.turn=false;
}else{
this.turn=true;
}
}
public boolean getTurn(){
return this.turn;
}
}
Now, the main can be:
public static void main(String[] args) {
SharedVariable vCom = new SharedVariable();
ThreadsExample1 hThread1 = new ThreadsExample1 (vCom);
ThreadsExample2 hThread2 = new ThreadsExample2 (vCom);
hThread1.start();
hThread2.start();
try {
hThread1.join();
hThread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
And you have to change your line static int counter = 1; // a global counter
for private SharedVariable counter;
And the new run is:
public void run() {
for (int i = 0; i < 20; i++) {
while (!counter.getTurno()){
Thread.yield();
}
System.out.println(this.counter.get());
this.counter.cambioTurno();
}
}
}
Yes, it is another code, but I think it can help you a little bit.

How to execute three thread simultaneously?

This is my code which i tried but my main class is not there because i don't know how to use that one
//first thread
class firstthread extends Thread
{
public void run(){
for(int i=0;i<1000;i++)
{
System.out.println(i);
}}
}
//second thread
class secondthread extends Thread
{
public void run(){
for(int i=0;i<1000;i++)
{
System.out.println(i);
}}
}
First overide the run method and then create the object of thread class in main()
and call start method.
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
new Thread() {
public void run() {
for(int y=0;y<1000;y++)
{
System.out.println(y);
}
};
}.start();
}
}
Whatever you have written is incomplete code, to create a thread you need to extend Thread class or implement Runnable interface and then override its public void run() method.
To create a thread you need to override the method public void run
Then to start the threads you need to call its start() method.
A simple complete example
class MyThread extends Thread {
String name;
public void run(){
for(int i=0;i<1000;i++) {
System.out.println("Thread name :: "+name+" : "i);
}
}
}
class Main{
public static void main(String args[]){
MyThread t1 = new MyThread();
t1.name = "Thread ONE";
MyThread t2 = new MyThread();
t2.name = "Thread TWO";
MyThread t3 = new MyThread();
t3.name = "Thread THREE";
t1.start();
t2.start();
t3.start();
}
}
You can't just put some code in your class body.
You need a method to have the code in, the method being run() in case of thread.
Instead of copy-pasting the code, I'll point you to the official documentation where you can find some examples.
Sample program given below. Since there is no synchronization code, there output is mixed from the three threads
public class ThreadTest implements Runnable{
#Override
public void run() {
System.out.print(Thread.currentThread().getId() + ": ");
for(int i=0;i<100;i++)
System.out.print(i + ", ");
System.out.println();
}
public static void main(String[] args) {
for(int i=0;i<3;i++){
new Thread(new ThreadTest()).start();
}
}
}

Regarding countdown latch implementation

I have been going through the program which starts three threads and print their corresponding value such that T3 is executed first, then the T1 thread, and lastly the T2 thread is executed. Below is the program.
I just want to know if you guys could help in converting this program with respect to countdown latch, as I want to develop it using this mechanism or it can be also done through counting semaphore.
From the answer to this related question:
public class Test {
static class Printer implements Runnable {
private final int from;
private final int to;
private Thread joinThread;
Printer(int from, int to, Thread joinThread) {
this.from = from;
this.to = to;
this.joinThread = joinThread;
}
#Override
public void run() {
if(joinThread != null) {
try {
joinThread.join();
} catch (InterruptedException e) { /* ignore for test purposes */ }
}
for (int i = from; i <= to; i++) {
System.out.println(i);
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread T3 = new Thread(new Printer(10, 15, null));
Thread T1 = new Thread(new Printer(1, 5, T3));
Thread T2 = new Thread(new Printer(6, 10, T1));
T1.start();
T2.start();
T3.start();
}
}
We consider each pair of threads Tw, Ts such as Tw is waiting on Ts to commence its work. In your setup, there are 2 such pairs:
T1, T3
T2, T1
For each pair, we will create one CountDownLatch, and provide it to each thread of the pair. Then Tw will call await on the latch before starting its work, and Ts will call countDown at the end of its own work.
Since T1 belongs to both pairs, it will receive both latches. However, in the first case, T1 is a waiting thread, and in the second, T1 is a signaling thread, therefore its code will have to be amended accordingly.
Of course you will have to remove the join calls and related infrastructure.
Since your question title asks about latch implementation, let's just briefly say that the same semantics can be produced using a Semaphore initialized at 0, and where countDown would actually be a release of the semaphore, while await would be an acquire of that semaphore.
public class Test {
private CountdownLatch latch;
private Runnable runnable;
class Tw implements Runnable {
Tw(CountdownLatch l, Runnable r) {
latch = l;
runnable = r;
}
#override
public void run(){
latch.await();
runnable.run();
}
}
class Ts implements Runnable {
CountdownLatch latch;
Runnable runnable;
Ts(CountdownLatch l, Runnable r){
latch = l;
runnable = r;
}
#override
public void run(){
runnable.run();
latch.countDown();
}
}
static class Printer implements Runnable {
private final int from;
private final int to;
Printer(int from, int to) {
this.from = from;
this.to = to;
}
#Override
public void run() {
for (int i = from; i <= to; i++) {
System.out.println(i);
}
}
public static void main(String[] args) throws InterruptedException {
CountdownLatch l31 = new CountdownLatch(1), l12 = new CountdownLatch(1);
Thread T3 = new Thread(new Ts(l31, new Printer(10, 15, null)));
Thread T1 = new Thread(new Tw(l31, new Ts(l12, new Printer(1, 5, T3))));
Thread T2 = new Thread(new Tw(l12, new Printer(6, 10, T1)));
T1.start();
T2.start();
T3.start();
}
}
The proposed sample implementation uses auxiliary runnables to take care of the latching process, thus allowing us to compose each task using these runnables, instead of deriving the Printer class for each specific case (we save at least one class).
The Semaphore based similar implementation is left as an exercise for the reader.

Categories

Resources