threads and synchronization example - java

I am new to Java. Below is a code as an example of threads and synchronization.
public class A implements Runnable{
public synchronized void run(){
/*
some code here
*/
}
}
public class B {
public static void main(String[] args){
A obj1 = new A();
Thread t = new Thread(obj1);
A obj2 = obj1;
Thread t1 = new Thread(obj2);
t.start();
t1.start();
}
}
Now will this two threads block each other for same lock or will they get two different locks?
Thank you!!

(First, please stick to the Java coding conventions. A class name should always start with a capital letter. No exceptions.)
Only one of the threads will execute the run() method at a time.
The A.run() method is an instance method, and it is declared as synchronized. These two facts mean that it will acquire a lock on this (i.e. the instance of A) before entering the method body, and release it on exiting. In short, run() locks this.
So in your main program you are creating a single A instance and passing it as the target object for two threads. They both need to execute the run() method on the same object, and this cannot happen at the same time ... by the reasoning of the previous paragraph.
This does not necessarily mean that one thread will block the other. It is also possible that the first thread to be started will have completed its run() call before the second thread is ready to try the call. But we can say ... definitively ... that the two threads' calls to run() will NOT overlap in time.

They will block each other, since they're both synchronized on the same object.
For example, this program:
public class Foo
{
public static void main(final String... args)
{
final Runnable r =
new Runnable()
{
public synchronized void run()
{
for(int i = 0; i < 10; ++i)
{
System.out.println(i);
try
{ Thread.sleep(1000L); }
catch(final InterruptedException ie)
{ throw new RuntimeException(ie); }
}
}
};
new Thread(r).start();
new Thread(r).start();
}
}
will print 0 through 9, pausing for a second after number, and then do it again. It will not interlace the two sets of numbers.

Synchronization forces the threads to run in order (block).
Synchronization, by definition, means that a method is run "one at a time". The first thread to be executed (likely "t") will thus complete before the 2nd thread (probably "t1")'s run() method is entered.
To test the synchronization effects:
The best experiment to run will be to fill the run() method with a call to
Thread.sleep(1000);
Then run your code with, and without the "synchronized" keyword, and time the programs execution .

The output of this code is getting intermixing of thread1 and thread0
package oopd;
/**
*
* #author mani deepak
*/
public class Oopd {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Deepak d,d1;
d=new Deepak();
d1=new Deepak();
Thread t,t1;
t=new Thread(d);
t1=new Thread(d1);
t.start();
t1.start();
}
}
class Deepak implements Runnable
{
#Override
public synchronized void run()
{
String s=Thread.currentThread().getName();
for(int i=0;i<10;i++)
{
try
{
Thread.sleep(100);
}
catch(Exception e)
{
}
System.out.println(s+" "+i);
}
}
}

Related

Java multi threading - run threads run method only once in sequence

In my applications there are an n number of actions that must happen, one after the other in sequence, for the whole life of the program. Instead of creating methods which implement those actions and calling them in order in a while(true) loop, I decided to create one thread for each action, and make them execute their run method once, then wait until all the other threads have done the same, wait for its turn, and re-execute again, and so on...
To implement this mechanism I created a class called StatusHolder, which has a single field called threadTurn (which signifies which thread should execute), a method to read this value, and one for updating it. (Note, this class uses the Singleton design pattern)
package Test;
public class StatusHolder
{
private static volatile StatusHolder statusHolderInstance = null;
public static volatile int threadTurn = 0;
public synchronized static int getTurn()
{
return threadTurn;
}
public synchronized static void nextTurn()
{
System.out.print("Thread turn: " + threadTurn + " --> ");
if (threadTurn == 1)
{
threadTurn = 0;
}
else
{
threadTurn++;
}
System.out.println(threadTurn);
//Wake up all Threads waiting on this obj for the right turn to come
synchronized (getStatusHolder())
{
getStatusHolder().notifyAll();
}
}
public static synchronized StatusHolder getStatusHolder()
{//Returns reference to this object
if (statusHolderInstance == null)
{
statusHolderInstance = new StatusHolder();
}
return statusHolderInstance;
}
}
Then I have, let's say, two threads which must be execute in the way explained above, t1 and t2.
T1 class looks like this:
package Test;
public class ThreadOne implements Runnable
{
#Override
public void run()
{
while (true)
{
ThreadUtils.waitForTurn(0);
//Execute job, code's not here for simplicity
System.out.println("T1 executed");
StatusHolder.nextTurn();
}
}
}
And T2 its the same, just change 0 to 1 in waitForTurn(0) and T1 to T2 in the print statement.
And my main is the following:
package Test;
public class Main
{
public static void main(String[] args) throws InterruptedException
{
Thread t1 = new Thread(new ThreadOne());
Thread t2 = new Thread(new ThreadTwo());
t1.start();
t2.start();
}
}
So the run method goes like this:
At the start of the loop the thread looks if it can act by checking the turn value with the waitForTurn() call:
package Test;
public class ThreadUtils
{
public static void waitForTurn(int codeNumber)
{ //Wait until turn value is equal to the given number
synchronized (StatusHolder.getStatusHolder())
{
while (StatusHolder.getTurn() != codeNumber)
{
try
{
StatusHolder.getStatusHolder().wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
If the two values are equal, the thread executes, otherwise it waits on the StatusHolder object to be awaken from the nextTurn() call, because when the turn value changes all the threads are awaken so that they can check if the new turn value is the one they are waiting for so they can run.
Note thatnextTurn() cycles between 0 and 1: that is because in this scenario I just have two threads, the first executes when the turn flag is 0, and the second when its 1, and then 0 again and so on. I can easily change the number of turns by changing this value.
The problem: If I run it, all goes well and seems to work, but suddenly the output console stops flowing, even if the program doesn't crash at all. I tried to put a t1.join() and then a print in the main but that print never executes, this means that the threads never stop/dies, but instead they remain locked sometimes.
This looks to be even more evident if I put three threads: it stops even sooner than with two threads.
I'm relatively new to threads, so I might be missing something really stupid here...
EDIT: I'd prefer not to delete a thread and create a new one every time: creating and deleting thousands of objs every second seems a big work load for the garbage collector.
The reason why I'm using threads and not functions is because in my real application (this code is just simplified) at a certain turn there actually are multiple threads that must run (in parallel), for example: turn 1 one thread, turn 2 one thread, turn 3 30 threads, repeat. So I thought why not creating threads also for the single functions and make the whole think sequential.
This is a bad approach. Multiple threads allow you to execute tasks concurrently. Executing actions "one after the other in sequence" is a job for a single thread.
Just do something like this:
List<Runnable> tasks = new ArrayList<>();
tasks.add(new ThreadOne()); /* Pick better names for tasks */
tasks.add(new ThreadTwo());
...
ExecutorService worker = Executors.newSingleThreadExecutor();
worker.submit(() -> {
while (!Thread.interrupted())
tasks.forEach(Runnable::run);
});
worker.shutdown();
Call worker.shutdownNow() when your application is cleanly exiting to stop these tasks at the end of their cycle.
you can use Semaphore class it's more simple
class t1 :
public class t1 implements Runnable{
private Semaphore s2;
private Semaphore s1;
public t1(Semaphore s1,Semaphore s2){
this.s1=s1;
this.s2=s2;
}
public void run()
{
while (true)
{
try {
s1.acquire();
} catch (InterruptedException ex) {
Logger.getLogger(t1.class.getName()).log(Level.SEVERE, null, ex);
}
//Execute job, code's not here for simplicity
System.out.println("T1 executed");
s2.release();
}
}
}
class t2:
public class t2 implements Runnable{
private Semaphore s2;
private Semaphore s1;
public t2(Semaphore s1,Semaphore s2){
this.s1=s1;
this.s2=s2;
}
public void run()
{
while (true)
{
try {
s2.acquire();
} catch (InterruptedException ex) {
Logger.getLogger(t2.class.getName()).log(Level.SEVERE, null, ex);
}
//Execute job, code's not here for simplicity
System.out.println("T2 executed");
s1.release();
}
}
}
class main:
public class Testing {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Semaphore s2=new Semaphore(0);
Semaphore s1=new Semaphore(1);
Thread th1 = new Thread(new t1(s1,s2));
Thread th2 = new Thread(new t2(s1,s2));
th1.start();
th2.start();
}}

Threading is not working correctly?

Doing a threading problem and I am not sure if this is how its supposed to be or if I coded incorrectly. From what I understand, threading should have multiple methods going at the same time and because of this they should be intertwined. My code is supposed to take a single char and repeat 1000 times but instead of having different variations of the two letters it goes "a" a thousand times, then "b" a thousand times. What is my issue?
Main Method
import java.util.*;
public class MainThread {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner answer = new Scanner(System.in);
System.out.println("Give me a single character: ");
char h = answer.next().charAt(0);
System.out.println("Give me another single character: ");
char a = answer.next().charAt(0);
MyThread t1 = new MyThread(h);
MyThread t2 = new MyThread(a);
t1.start(h);
t2.start(a);
answer.close();
}
}
my Threading class
import java.util.*;
public class MyThread extends Thread{
Scanner answer = new Scanner(System.in);
public MyThread(char x) {
// TODO Auto-generated constructor stub
}
public void Stored(char x){
System.out.println("Type a single letter here: ");
}
//modified run method
public void start(char x){
for(int i = 0; i < 1000; i++){
System.out.print(x);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.yield();
}
}
}
What you have done is NOT multithreading, rather you have called the start method sequentially, i.e., in order to run the multiple threads parallelly, you need to override the run() method in your MyThread class.
The important point is that run() method will be called by JVM automatically when you start the Thread, and the code inside run() will be executed in parallel with the main/other threads, so override run() inside MyThread class as shown below:
class MyThread extends Thread {
private char x;
public MyThread(char x) {
this.x= x;
}
// Add run() method
public void run() {
for (int i = 0; i < 10; i++) {
System.out.print(x);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.yield();
}
}
}
MainThread class:
public class MainThread {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner answer = new Scanner(System.in);
System.out.println("Give me a single character: ");
char h = answer.next().charAt(0);
System.out.println("Give me another single character: ");
char a = answer.next().charAt(0);
MyThread t1 = new MyThread(h);
MyThread t2 = new MyThread(a);
t1.start();//this calls run() of t1 automatically
t2.start();//this calls run() of t2 automatically
answer.close();
}
}
I suggest you have a look here for basic understanding on how to create and start the Thread and how multi-threading works.
In order to let the threads run in parallel, the run method needs to be implemented instead of start.
See the JavaDoc for Thread.start():
Causes this thread to begin execution; the Java Virtual Machine calls
the run method of this thread.
The result is that two threads are running concurrently: the current
thread (which returns from the call to the start method) and the
other thread (which executes its run method).
First of all, it's not guaranteed that your described behavior will never occur, even when you implement a correct multithreading. But, it shouldn't be repeatable ;)
The solution is: don't override the start() but the run() method.
The thread constructor should take the argument, the start() is called (and no new start method with an argument!) from the main, and the run() implements the job that is executed parallel. Therefore, you can access the thread's field which you set in your thread constructor.
The error was already explained: the start method is being overridden instead of the run method. Anyway it is not recommended to extend the Thread class since you are not wanting to extend its functionality.
You just want to use a Thread, so a better approach (IMO) is to provide a Runnable to the Thread:
public static void main(String[] args) {
// ...
Thread t1 = new Thread(new MyRunnable(h));
t1.start();
}
The Runnable (use a better Name in production code):
public class MyRunnable implements Runnable {
private final char ch;
public MyRunnable(char theChar) {
ch = theChar;
}
#Override
public void run() {
for (int i = 0; i < 1000; i++) {
...
}
}
This could be improved using with Lambda, but is not the point here
More: "implements Runnable" vs. "extends Thread"

java thread not running even after start call

public class TestSynchronization {
public static void main(String[] args) {
ThreadTest[] threads = new ThreadTest[10];
int i = 0;
for(Thread th : threads) {
th = new Thread(Integer.toString(i++));
th.start();
}
}
class ThreadTest extends Thread {
TestSynchronization ts = new TestSynchronization();
public /*synchronized */void run() {
synchronized(this) {
ts.testingOneThreadEntry(this);
System.out.println(new Date());
System.out.println("Hey! I just came out and it was fun... ");
this.notify();
}
}
}
private synchronized void testingOneThreadEntry(Thread threadInside) {
System.out.println(threadInside.getName() + " is in");
System.out.println("Hey! I am inside and I am enjoying");
try {
threadInside.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I am not able to start the ThreadTest instances.
I expect that ThreadTest's run method be executed as soon as the line th.start(); is executed, the one inside main method.
When I run the program, I see niether my system.out nor any exception.
I debugged also, but could see loop runs 10 times.
You just started a Thread, not a ThreadTest. Thread's run() method does nothing. Instead, create and start() a ThreadTest.
for(ThreadTest th : threads) {
th = new ThreadTest(Integer.toString(i++));
th.start();
}
You'll also need a one-arg constructor in your ThreadTest class that will take the String you're passing to it.
public ThreadTest(String msg){
super(msg);
}
You'll also need to make the ThreadTest class static so you can access that nested class from the static main method.
static class ThreadTest extends Thread {
However, you'll wind up will all Threads waiting. As written, this code will call wait inside every Thread, but it will never get to notify. The notify method must be called on the Thread to be notified, from another Thread. If it's waiting, then it can never notify itself.
You have array of ThreadTest (thread) class which is not used.
I assume you wanted this:
public static void main(String[] args) {
ThreadTest[] threads = new ThreadTest[10];
int i = 0;
for(int i=0;i<threads.length;i++) {
threads[i] = new ThreadTest();
threads[i].start();
}
}

Thread able to see the updated static variable set by the main thread in java

can you please clarify me what is the problem with code:
Q: Even though i am not declaring the blinker as volatile, but thread t1 able to see the updated value(true) set by the main thread….
code:
package com.learning;
public class HowToStopRunningThread implements Runnable{
/**
* #param args
*/
public static boolean blinker;
public static void main(String[] args) {
Thread t = new Thread(new HowToStopRunningThread());
t.start();
HowToStopRunningThread obj = new HowToStopRunningThread();
obj.stop();
}
public void stop(){
try{
Thread.sleep(100);
System.out.println(“Setting the Blinker value”);
blinker = true;
}catch(InterruptedException ie){
ie.getMessage();
}
}
#Override
public void run() {
while(!blinker){
try{
System.out.println(“blinker:”+blinker);
Thread.sleep(1000);
}catch(InterruptedException ie){
ie.getMessage();
}
}
}
}
Output:
blinker:false
Setting the Blinker value
———————————
and then thread came out of the while loop
volatile guarantees that the new value will be visible by other threads. But that doesn't mean that changes to non-volatile variables are guaranteed to be invisible.
In short, this works by accident, and is not guaranteed to work always and everywhere.
In this case, it certainly works because both threads print to System.out, and println is a synchronized method. And synchronized also offers visibility guarantees.

Wrapping a dead thread object in new thread object to restart it

I want to restart a thread for some use, for example in the below code.
class Ex13 implements Runnable {
int i = 0;
public void run() {
System.out.println("Running " + ++i);
}
public static void main(String[] args) throws Exception {
Thread th1 = new Thread(new Ex13(), "th1");
th1.start();
//th1.join()
Thread th2 = new Thread(th1);
th2.start();
}
}
When I'm executing the above program , some time i'm getting the output as
Running 1
Running 2
and some time i'm getting only
Running 1
After few run i'm getting only
Running 1 as output.
I'm totally surprise about this behavior. Can any one help me understand this.
if I put the join() then i'm getting only Running 1.
You reuse Thread instance, not Runnable. Thread overwrites its run() method to
public void run() {
if (target != null) {
target.run();
}
}
Where target is the Runnable that you give to the constructor. besides that, Thread has an exit() method that is called by the VM, and this method sets target to null (the reason is this bug). So if your first thread has the chance to finish its execution, its run() method is pretty much empty. Adding th1.join() proves it.
If you want to keep some state, you need to keep reference to your Runnable instance, not the Thread. This way run() method will not be altered.
I don't know why do you need this, but (please note that this code doesn't ensure that th1 is ALWAYS executed before th2, though) :
public static class Ex13 implements Runnable {
AtomicInteger i = new AtomicInteger(0);
CountDownLatch latch;
Ex13(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
System.out.println("Running " + i.incrementAndGet());
latch.countDown();
}
}
public static void main(String[] args) throws Exception {
CountDownLatch latch = new CountDownLatch(2);
Ex13 r = new Ex13(latch);
Thread th1 = new Thread(r, "th1");
th1.start();
Thread th2 = new Thread(r);
th2.start();
latch.await(); // wait until both theads are executed
System.out.println("Done");
}
You want the incrementing of i to be synchronized, i.e.
public class Ex13 implements Runnable {
int i=0;
public void run() {
    System.out.println("Running "+ increment());
}
private synchronized int increment() {
return ++i;
}
}
The Java Tutorial has a very nice explanation of this given a very similar scenario. The problem is that incrementing a variable is not an atomic operation. Each thread needs to read the current state of i before setting it to the new value. Restricting access to incrementing the variable to one thread at a time assures you will get consistent behavior.
To see whats happening in the System.out.println you can also print the thread name:
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" + name);
I see you call the two threads with the same runnable object, so they will both use the same "i" variable, in order for you to get Running 1 Running 2 you need to synchronize "i"

Categories