A Java beginner question regarding multi-threadingIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Does a finally block always get executed in Java?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?“implements Runnable” vs “extends Thread” in JavaHow do I convert a String to an int in Java?Creating a memory leak with Java

How to honestly answer questions from a girlfriend like "How did you find this place" without giving the impression I'm always talking about my exes?

Why doesn't philosophy have higher standards for its arguments?

What is this old "lemon-squeezer" shaped pan

Why does the Trade Federation become so alarmed upon learning the ambassadors are Jedi Knights?

Construct a pentagon avoiding compass use

Are L-functions uniquely determined by their values at negative integers?

Can both line and load go to same screw on a GFCI outlet?

Can you perfectly wrap a cube with this blocky shape?

Is `curl something | sudo bash -` a reasonably safe installation method?

What are the arguments for California’s nonpartisan blanket primaries?

Do aircraft cabins have suspension?

Could the crash sites of the Apollo 11 and 16 LMs be seen by the LRO?

I quit, and boss offered me 3 month "grace period" where I could still come back

How to change checkbox react correctly?

Problem with interpolating function returned by NDEigensystem

Mathematica function equivalent to Matlab's residue function (partial fraction expansion)

Will it hurt my career to work as a graphic designer in a startup for beauty and skin care?

How to calculate difference in AnyDice?

Why do the faithful have to say "And with your spirit " in Catholic Mass?

How to unload a Mathematica package?

Can I send medicine to someone in Canada?

How could an animal "smell" carbon monoxide?

What impact would a dragon the size of Asia have on the environment?

Why don't commercial aircraft adopt a slightly more seaplane-like design to allow safer ditching in case of emergency?



A Java beginner question regarding multi-threading


Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Does a finally block always get executed in Java?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?“implements Runnable” vs “extends Thread” in JavaHow do I convert a String to an int in Java?Creating a memory leak with Java






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm brushing up my java skills after years of not using it. Recently, I've been reading a chapter on multi-threading that mentions:



"However—what if you have a non-static method that accesses a static field?
Or a static method that accesses a non-static field (using an instance)? In
these cases things start to get messy quickly, and there's a very good chance that
things will not work the way you want. If you've got a static method accessing a
non-static field, and you synchronize the method, you acquire a lock on the Class
object. But what if there's another method that also accesses the non-static field,
this time using a non-static method? It probably synchronizes on the current
instance (this) instead. Remember that a static synchronized method and a
non-static synchronized method will not block each other—they can run at
the same time.
"



For the sake of learning, I've been trying to code an example where a scenario that was cited on the snippet above: A program in which a static synchronized method that modifies a non-static field running at the same time with a non-synchronized method.



So, far I was not successful in doing this. A bit of help is appreciated. Thanks!



Below is the sample of a code I have done. However, as expected, the threads do not run at the same time since they are synchronized. I just wanted to see an example mentioned on the book so I will know what not to do.



class code147_class1
int num1 = 111;
static int num2 = 222;

//code147_class1


public class code147 implements Runnable

code147_class1 z = new code147_class1();

public static void main (String args[])
System.out.println("Program has started...");
System.out.println("The value of the instance variable is:"+new code147_class1().num1);
System.out.println("The value of the static variable is:"+code147_class1.num2);

code147 cd1 = new code147();

Thread thread1 = new Thread(cd1);
Thread thread2 = new Thread(cd1);

thread1.start();
thread2.start();


//main

public void run()
System.out.println("Thread has started for:"+Thread.currentThread().getId());

try
subtract_instance_var(z);
Thread.sleep(100);
code147.static_subtract_instance_var(z);

catch(Exception ex)


//run

public synchronized void subtract_instance_var(code147_class1 x)
if(x.num1 ==111)

try
Thread.sleep(100);

catch(Exception ex)


x.num1 = x.num1 - 11;
System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());

//if

System.out.println("The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

//subtract_instance_var

public synchronized static void static_subtract_instance_var(code147_class1 x)
if (x.num1==111)
try
Thread.sleep(100);

catch(InterruptedException ex)
//catch
x.num1 = x.num1 -11;
System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());
//if

System.out.println("STATIC The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

//stati_subtract_var

//class


After running the code, I was expecting the value of the instance variable to be 89. The program however results in 100.










share|improve this question






















  • And what's the result?

    – Andronicus
    Mar 26 at 7:24











  • The static and instance methods don't block each other, but since you execute one after the other, that's not relevant inside the thread, and since you synchronize on the same instance of code147, the instance method is not invoked concurrently either.

    – Andy Turner
    Mar 26 at 7:33











  • Hi Andronicus, the output of the programs is: STATIC The value of instance variable at the end for thread: 12 is 100 STATIC The value of instance variable at the end for thread: 11 is 100 I was expecting to 89. Since I am trying to have the both the static and non-static to run together subtract 11 at the same time to the variable.

    – jpibay
    Mar 26 at 7:35












  • Hi Andy Turner, thanks for your input. I was hoping that the sleep method will allow the other thread to run the instance method while the other one is running the static. I am not sure what I'm doing anymore :) . Any advice how to go about doing an example from the book? thanks!

    – jpibay
    Mar 26 at 7:44











  • @jpibay it doesnt. sleep does not release the monitor.

    – Andy Turner
    Mar 26 at 7:46

















0















I'm brushing up my java skills after years of not using it. Recently, I've been reading a chapter on multi-threading that mentions:



"However—what if you have a non-static method that accesses a static field?
Or a static method that accesses a non-static field (using an instance)? In
these cases things start to get messy quickly, and there's a very good chance that
things will not work the way you want. If you've got a static method accessing a
non-static field, and you synchronize the method, you acquire a lock on the Class
object. But what if there's another method that also accesses the non-static field,
this time using a non-static method? It probably synchronizes on the current
instance (this) instead. Remember that a static synchronized method and a
non-static synchronized method will not block each other—they can run at
the same time.
"



For the sake of learning, I've been trying to code an example where a scenario that was cited on the snippet above: A program in which a static synchronized method that modifies a non-static field running at the same time with a non-synchronized method.



So, far I was not successful in doing this. A bit of help is appreciated. Thanks!



Below is the sample of a code I have done. However, as expected, the threads do not run at the same time since they are synchronized. I just wanted to see an example mentioned on the book so I will know what not to do.



class code147_class1
int num1 = 111;
static int num2 = 222;

//code147_class1


public class code147 implements Runnable

code147_class1 z = new code147_class1();

public static void main (String args[])
System.out.println("Program has started...");
System.out.println("The value of the instance variable is:"+new code147_class1().num1);
System.out.println("The value of the static variable is:"+code147_class1.num2);

code147 cd1 = new code147();

Thread thread1 = new Thread(cd1);
Thread thread2 = new Thread(cd1);

thread1.start();
thread2.start();


//main

public void run()
System.out.println("Thread has started for:"+Thread.currentThread().getId());

try
subtract_instance_var(z);
Thread.sleep(100);
code147.static_subtract_instance_var(z);

catch(Exception ex)


//run

public synchronized void subtract_instance_var(code147_class1 x)
if(x.num1 ==111)

try
Thread.sleep(100);

catch(Exception ex)


x.num1 = x.num1 - 11;
System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());

//if

System.out.println("The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

//subtract_instance_var

public synchronized static void static_subtract_instance_var(code147_class1 x)
if (x.num1==111)
try
Thread.sleep(100);

catch(InterruptedException ex)
//catch
x.num1 = x.num1 -11;
System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());
//if

System.out.println("STATIC The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

//stati_subtract_var

//class


After running the code, I was expecting the value of the instance variable to be 89. The program however results in 100.










share|improve this question






















  • And what's the result?

    – Andronicus
    Mar 26 at 7:24











  • The static and instance methods don't block each other, but since you execute one after the other, that's not relevant inside the thread, and since you synchronize on the same instance of code147, the instance method is not invoked concurrently either.

    – Andy Turner
    Mar 26 at 7:33











  • Hi Andronicus, the output of the programs is: STATIC The value of instance variable at the end for thread: 12 is 100 STATIC The value of instance variable at the end for thread: 11 is 100 I was expecting to 89. Since I am trying to have the both the static and non-static to run together subtract 11 at the same time to the variable.

    – jpibay
    Mar 26 at 7:35












  • Hi Andy Turner, thanks for your input. I was hoping that the sleep method will allow the other thread to run the instance method while the other one is running the static. I am not sure what I'm doing anymore :) . Any advice how to go about doing an example from the book? thanks!

    – jpibay
    Mar 26 at 7:44











  • @jpibay it doesnt. sleep does not release the monitor.

    – Andy Turner
    Mar 26 at 7:46













0












0








0


1






I'm brushing up my java skills after years of not using it. Recently, I've been reading a chapter on multi-threading that mentions:



"However—what if you have a non-static method that accesses a static field?
Or a static method that accesses a non-static field (using an instance)? In
these cases things start to get messy quickly, and there's a very good chance that
things will not work the way you want. If you've got a static method accessing a
non-static field, and you synchronize the method, you acquire a lock on the Class
object. But what if there's another method that also accesses the non-static field,
this time using a non-static method? It probably synchronizes on the current
instance (this) instead. Remember that a static synchronized method and a
non-static synchronized method will not block each other—they can run at
the same time.
"



For the sake of learning, I've been trying to code an example where a scenario that was cited on the snippet above: A program in which a static synchronized method that modifies a non-static field running at the same time with a non-synchronized method.



So, far I was not successful in doing this. A bit of help is appreciated. Thanks!



Below is the sample of a code I have done. However, as expected, the threads do not run at the same time since they are synchronized. I just wanted to see an example mentioned on the book so I will know what not to do.



class code147_class1
int num1 = 111;
static int num2 = 222;

//code147_class1


public class code147 implements Runnable

code147_class1 z = new code147_class1();

public static void main (String args[])
System.out.println("Program has started...");
System.out.println("The value of the instance variable is:"+new code147_class1().num1);
System.out.println("The value of the static variable is:"+code147_class1.num2);

code147 cd1 = new code147();

Thread thread1 = new Thread(cd1);
Thread thread2 = new Thread(cd1);

thread1.start();
thread2.start();


//main

public void run()
System.out.println("Thread has started for:"+Thread.currentThread().getId());

try
subtract_instance_var(z);
Thread.sleep(100);
code147.static_subtract_instance_var(z);

catch(Exception ex)


//run

public synchronized void subtract_instance_var(code147_class1 x)
if(x.num1 ==111)

try
Thread.sleep(100);

catch(Exception ex)


x.num1 = x.num1 - 11;
System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());

//if

System.out.println("The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

//subtract_instance_var

public synchronized static void static_subtract_instance_var(code147_class1 x)
if (x.num1==111)
try
Thread.sleep(100);

catch(InterruptedException ex)
//catch
x.num1 = x.num1 -11;
System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());
//if

System.out.println("STATIC The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

//stati_subtract_var

//class


After running the code, I was expecting the value of the instance variable to be 89. The program however results in 100.










share|improve this question














I'm brushing up my java skills after years of not using it. Recently, I've been reading a chapter on multi-threading that mentions:



"However—what if you have a non-static method that accesses a static field?
Or a static method that accesses a non-static field (using an instance)? In
these cases things start to get messy quickly, and there's a very good chance that
things will not work the way you want. If you've got a static method accessing a
non-static field, and you synchronize the method, you acquire a lock on the Class
object. But what if there's another method that also accesses the non-static field,
this time using a non-static method? It probably synchronizes on the current
instance (this) instead. Remember that a static synchronized method and a
non-static synchronized method will not block each other—they can run at
the same time.
"



For the sake of learning, I've been trying to code an example where a scenario that was cited on the snippet above: A program in which a static synchronized method that modifies a non-static field running at the same time with a non-synchronized method.



So, far I was not successful in doing this. A bit of help is appreciated. Thanks!



Below is the sample of a code I have done. However, as expected, the threads do not run at the same time since they are synchronized. I just wanted to see an example mentioned on the book so I will know what not to do.



class code147_class1
int num1 = 111;
static int num2 = 222;

//code147_class1


public class code147 implements Runnable

code147_class1 z = new code147_class1();

public static void main (String args[])
System.out.println("Program has started...");
System.out.println("The value of the instance variable is:"+new code147_class1().num1);
System.out.println("The value of the static variable is:"+code147_class1.num2);

code147 cd1 = new code147();

Thread thread1 = new Thread(cd1);
Thread thread2 = new Thread(cd1);

thread1.start();
thread2.start();


//main

public void run()
System.out.println("Thread has started for:"+Thread.currentThread().getId());

try
subtract_instance_var(z);
Thread.sleep(100);
code147.static_subtract_instance_var(z);

catch(Exception ex)


//run

public synchronized void subtract_instance_var(code147_class1 x)
if(x.num1 ==111)

try
Thread.sleep(100);

catch(Exception ex)


x.num1 = x.num1 - 11;
System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());

//if

System.out.println("The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

//subtract_instance_var

public synchronized static void static_subtract_instance_var(code147_class1 x)
if (x.num1==111)
try
Thread.sleep(100);

catch(InterruptedException ex)
//catch
x.num1 = x.num1 -11;
System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());
//if

System.out.println("STATIC The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

//stati_subtract_var

//class


After running the code, I was expecting the value of the instance variable to be 89. The program however results in 100.







java






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 26 at 7:21









jpibayjpibay

61 bronze badge




61 bronze badge












  • And what's the result?

    – Andronicus
    Mar 26 at 7:24











  • The static and instance methods don't block each other, but since you execute one after the other, that's not relevant inside the thread, and since you synchronize on the same instance of code147, the instance method is not invoked concurrently either.

    – Andy Turner
    Mar 26 at 7:33











  • Hi Andronicus, the output of the programs is: STATIC The value of instance variable at the end for thread: 12 is 100 STATIC The value of instance variable at the end for thread: 11 is 100 I was expecting to 89. Since I am trying to have the both the static and non-static to run together subtract 11 at the same time to the variable.

    – jpibay
    Mar 26 at 7:35












  • Hi Andy Turner, thanks for your input. I was hoping that the sleep method will allow the other thread to run the instance method while the other one is running the static. I am not sure what I'm doing anymore :) . Any advice how to go about doing an example from the book? thanks!

    – jpibay
    Mar 26 at 7:44











  • @jpibay it doesnt. sleep does not release the monitor.

    – Andy Turner
    Mar 26 at 7:46

















  • And what's the result?

    – Andronicus
    Mar 26 at 7:24











  • The static and instance methods don't block each other, but since you execute one after the other, that's not relevant inside the thread, and since you synchronize on the same instance of code147, the instance method is not invoked concurrently either.

    – Andy Turner
    Mar 26 at 7:33











  • Hi Andronicus, the output of the programs is: STATIC The value of instance variable at the end for thread: 12 is 100 STATIC The value of instance variable at the end for thread: 11 is 100 I was expecting to 89. Since I am trying to have the both the static and non-static to run together subtract 11 at the same time to the variable.

    – jpibay
    Mar 26 at 7:35












  • Hi Andy Turner, thanks for your input. I was hoping that the sleep method will allow the other thread to run the instance method while the other one is running the static. I am not sure what I'm doing anymore :) . Any advice how to go about doing an example from the book? thanks!

    – jpibay
    Mar 26 at 7:44











  • @jpibay it doesnt. sleep does not release the monitor.

    – Andy Turner
    Mar 26 at 7:46
















And what's the result?

– Andronicus
Mar 26 at 7:24





And what's the result?

– Andronicus
Mar 26 at 7:24













The static and instance methods don't block each other, but since you execute one after the other, that's not relevant inside the thread, and since you synchronize on the same instance of code147, the instance method is not invoked concurrently either.

– Andy Turner
Mar 26 at 7:33





The static and instance methods don't block each other, but since you execute one after the other, that's not relevant inside the thread, and since you synchronize on the same instance of code147, the instance method is not invoked concurrently either.

– Andy Turner
Mar 26 at 7:33













Hi Andronicus, the output of the programs is: STATIC The value of instance variable at the end for thread: 12 is 100 STATIC The value of instance variable at the end for thread: 11 is 100 I was expecting to 89. Since I am trying to have the both the static and non-static to run together subtract 11 at the same time to the variable.

– jpibay
Mar 26 at 7:35






Hi Andronicus, the output of the programs is: STATIC The value of instance variable at the end for thread: 12 is 100 STATIC The value of instance variable at the end for thread: 11 is 100 I was expecting to 89. Since I am trying to have the both the static and non-static to run together subtract 11 at the same time to the variable.

– jpibay
Mar 26 at 7:35














Hi Andy Turner, thanks for your input. I was hoping that the sleep method will allow the other thread to run the instance method while the other one is running the static. I am not sure what I'm doing anymore :) . Any advice how to go about doing an example from the book? thanks!

– jpibay
Mar 26 at 7:44





Hi Andy Turner, thanks for your input. I was hoping that the sleep method will allow the other thread to run the instance method while the other one is running the static. I am not sure what I'm doing anymore :) . Any advice how to go about doing an example from the book? thanks!

– jpibay
Mar 26 at 7:44













@jpibay it doesnt. sleep does not release the monitor.

– Andy Turner
Mar 26 at 7:46





@jpibay it doesnt. sleep does not release the monitor.

– Andy Turner
Mar 26 at 7:46












3 Answers
3






active

oldest

votes


















1














The result 100 you got is correct.
thread1 and thread2 will run at the same time. Since "subtract_instance_var" method is synchronized one thread will make the variable 100. Then that thread will go to sleep. As the lock is released other thread can execute "subtract_instance_var". But nothing will happen as "x.num1==111" condition fails. After sleep when both the threads try to execute "static_subtract_instance_var" method still "x.num1==111" condition fails. So variable value remains 100.






share|improve this answer























  • Hi @nuwan, thanks for your input. Yes, 100 I got is correct . But I am aiming to have a result of 89. I wanted to have an example where even there are synchronized methods (instance and static) in place, even with the checking of "x.num1==111", both methods still ran at the same time and both subtracted 11 at the same variable. And at the end variable result is 89.

    – jpibay
    Mar 27 at 5:50



















1














Your example code does not execute the static substraction and the instance substraction at the same time. So no Thread-safety is engaged.



Also,your code only substracts 11 if the original value is 111. So your result is 100.



Here is an alternate main that will execute substract and static_substract in concurrency.



public static void main(String args[]) 
System.out.println("Program has started...");
System.out.println("The value of the instance variable is:" + new Code147_class1().num1);
System.out.println("The value of the static variable is:" + Code147_class1.num2);

Code147 cd1 = new Code147();

Thread thread1 = new Thread(() ->
IntStream.range(0, 5).forEach(i->
cd1.subtract_instance_var(cd1.z);
);
, "instance thread");
Thread thread2 = new Thread(() ->
IntStream.range(0, 5).forEach(i->
static_subtract_instance_var(cd1.z);
);
, "static thread");

thread1.start();
thread2.start();

// main


Notice that in this code two threads substract 11, 5 times each, from the initial 111. The left over should be 1. It won't always be, because of thread safety.



Complete code with thread safety problem



import java.util.stream.IntStream;

class Code147_class1
int num1 = 111;

// Code147_OK_class1

public class Code147

Code147_OK_class1 z = new Code147_OK_class1();

public static void main(String args[])
System.out.println("Program has started...");
System.out.println("The value of the instance variable is:" + new Code147_OK_class1().num1);

Code147 cd1 = new Code147();

Thread thread1 = new Thread(() ->
IntStream.range(0, 5).forEach(i ->
System.out.println("tInstance Substract 11 #" + (i + 1));
cd1.subtract_instance_var(cd1.z);
);
, "instance thread");
Thread thread2 = new Thread(() ->
IntStream.range(0, 5).forEach(i ->
System.out.println("tStatic Substract 11 #" + (i + 1));
static_subtract_instance_var(cd1.z);
);
, "static thread");

thread1.start();
thread2.start();

// main

public synchronized void subtract_instance_var(Code147_OK_class1 x)
// if (x.num1 == 111)

try
Thread.sleep(100);
catch (Exception ex)


x.num1 = x.num1 - 11;
System.out.println("Value is subtracted at thread T" + Thread.currentThread().getId());

// // if

System.out.println("The value of instance variable at the end for thread T" + Thread.currentThread().getId()
+ " is " + x.num1);

// subtract_instance_var

public synchronized static void static_subtract_instance_var(Code147_OK_class1 x)
// if (x.num1 == 111)
try
Thread.sleep(100);
catch (InterruptedException ex)
// catch
x.num1 = x.num1 - 11;
System.out.println("STATIC Value is subtracted at thread T" + Thread.currentThread().getId());
// // if

System.out.println("STATIC The value of instance variable at the end for thread T"
+ Thread.currentThread().getId() + " is " + x.num1);

// stati_subtract_var

// class


Example Output




Program has started...
The value of the instance variable is:111
Instance Substract 11 #1
Static Substract 11 #1
STATIC Value is subtracted at thread T11
STATIC The value of instance variable at the end for thread T11 is 89
Static Substract 11 #2
Value is subtracted at thread T10
The value of instance variable at the end for thread T10 is 89
Instance Substract 11 #2
Value is subtracted at thread T10
STATIC Value is subtracted at thread T11
The value of instance variable at the end for thread T10 is 67
Instance Substract 11 #3
STATIC The value of instance variable at the end for thread T11 is 67
Static Substract 11 #3
STATIC Value is subtracted at thread T11
Value is subtracted at thread T10
The value of instance variable at the end for thread T10 is 45
Instance Substract 11 #4
STATIC The value of instance variable at the end for thread T11 is 45
Static Substract 11 #4
Value is subtracted at thread T10
STATIC Value is subtracted at thread T11
The value of instance variable at the end for thread T10 is 23
Instance Substract 11 #5
STATIC The value of instance variable at the end for thread T11 is 23
Static Substract 11 #5
Value is subtracted at thread T10
The value of instance variable at the end for thread T10 is 12
STATIC Value is subtracted at thread T11
STATIC The value of instance variable at the end for thread T11 is 12


Notice the last value is 12, not 1...



Complete code with thread safety fixed



You could make your program thread safe by synchronizing on the same monitor, say z in this example :



import java.util.stream.IntStream;

class Code147_OK_class1
int num1 = 111;

// Code147_OK_class1

public class Code148_OK

Code147_class1 z = new Code147_class1();

public static void main(String args[])
System.out.println("Program has started...");
System.out.println("The value of the instance variable is:" + new Code147_class1().num1);

Code148_OK cd1 = new Code148_OK();

Thread thread1 = new Thread(() ->
IntStream.range(0, 5).forEach(i ->
System.out.println("tInstance Substract 11 #" + (i + 1));
cd1.subtract_instance_var(cd1.z);
);
, "instance thread");
Thread thread2 = new Thread(() ->
IntStream.range(0, 5).forEach(i ->
System.out.println("tStatic Substract 11 #" + (i + 1));
static_subtract_instance_var(cd1.z);
);
, "static thread");

thread1.start();
thread2.start();

// main

public /* synchronized */ void subtract_instance_var(Code147_class1 x)
synchronized (x)
// if (x.num1 == 111)

try
Thread.sleep(100);
catch (Exception ex)


x.num1 = x.num1 - 11;
System.out.println("Value is subtracted at thread T" + Thread.currentThread().getId());

// // if

System.out.println("The value of instance variable at the end for thread T" + Thread.currentThread().getId()
+ " is " + x.num1);


// subtract_instance_var

public /* synchronized */ static void static_subtract_instance_var(Code147_class1 x)
synchronized (x)
// if (x.num1 == 111)
try
Thread.sleep(100);
catch (InterruptedException ex)
// catch
x.num1 = x.num1 - 11;
System.out.println("STATIC Value is subtracted at thread T" + Thread.currentThread().getId());
// // if

System.out.println("STATIC The value of instance variable at the end for thread T"
+ Thread.currentThread().getId() + " is " + x.num1);


// stati_subtract_var

// class


Output




Program has started...
The value of the instance variable is:111
Instance Substract 11 #1
Static Substract 11 #1
Value is subtracted at thread T10
The value of instance variable at the end for thread T10 is 100
Instance Substract 11 #2
STATIC Value is subtracted at thread T11
STATIC The value of instance variable at the end for thread T11 is 89
Static Substract 11 #2
Value is subtracted at thread T10
The value of instance variable at the end for thread T10 is 78
Instance Substract 11 #3
STATIC Value is subtracted at thread T11
STATIC The value of instance variable at the end for thread T11 is 67
Static Substract 11 #3
Value is subtracted at thread T10
The value of instance variable at the end for thread T10 is 56
Instance Substract 11 #4
STATIC Value is subtracted at thread T11
STATIC The value of instance variable at the end for thread T11 is 45
Static Substract 11 #4
Value is subtracted at thread T10
The value of instance variable at the end for thread T10 is 34
Instance Substract 11 #5
STATIC Value is subtracted at thread T11
STATIC The value of instance variable at the end for thread T11 is 23
Static Substract 11 #5
Value is subtracted at thread T10
The value of instance variable at the end for thread T10 is 12
STATIC Value is subtracted at thread T11
STATIC The value of instance variable at the end for thread T11 is 1


Tell me if the java 8 lambda stuff is unclear, I will rewrite it with "classic" Runnables and loops.



HTH!






share|improve this answer























  • Thank you so much @Highbrainer ! Your post helped me a lot. The key for me is that I didn't realize that you could actually specify what specific method to run for a runnable class when initiating a thread. (and also learning lambda expressions on the fly. I haven't yet learned that part from the book lol.) Actually came up with my own solution based on what is advised from the book. I will post it in here. Again Thanks!

    – jpibay
    Mar 27 at 5:31











  • Based on the book it is mentioned there: To keep things simple: in order to make a class thread-safe, methods that access changeable fields need to be synchronized. Access to static fields should be done from static synchronized methods. Access to non-static fields should be done from non-static synchronize method

    – jpibay
    Mar 27 at 5:35












  • Here is my solution:

    – jpibay
    Mar 27 at 5:38


















0














With inputs from @Highbrainer, I managed to get a program to run 2 threads with 1 running a synchronized instance method and another running a static method. Both modifying an instance field. As advised from the book, to prevent this kind of problem, we should always be modifying instance fields from an instance method and static fields from a s static method. I just modified the program to change the static method to an instance method.



class code148_class1
int num1 = 111;

//code148_class1


public class code148 implements Runnable

static code148_class1 z = new code148_class1();

public static void main (String args[])
System.out.println("Program has started...");
System.out.println("The value of the instance variable is:"+z.num1);

code148 cd1 = new code148();

Thread thread1 = new Thread(
()->
cd1.subtract_instance_var(z);

);
Thread thread2 = new Thread(
()->
cd1.NONstatic_subtract_instance_var(z);

);

thread1.start();
thread2.start();


//main

public void run()
System.out.println("Thread has started for:"+Thread.currentThread().getId());

// try
// subtract_instance_var(z);
// Thread.sleep(100);
// code148.static_subtract_instance_var(z);
//
// catch(Exception ex)
//
//
//run

public synchronized void subtract_instance_var(code148_class1 x)
if(x.num1 ==111)

try
Thread.sleep(100);

catch(Exception ex)


x.num1 = x.num1 - 11;
System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());

//if

System.out.println("The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

//subtract_instance_var

public synchronized void NONstatic_subtract_instance_var(code148_class1 x)
if (x.num1==111)
try
Thread.sleep(100);

catch(InterruptedException ex)
//catch
x.num1 = x.num1 -11;
System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());
//if

System.out.println("STATIC The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

//stati_subtract_var

//class





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55351694%2fa-java-beginner-question-regarding-multi-threading%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    The result 100 you got is correct.
    thread1 and thread2 will run at the same time. Since "subtract_instance_var" method is synchronized one thread will make the variable 100. Then that thread will go to sleep. As the lock is released other thread can execute "subtract_instance_var". But nothing will happen as "x.num1==111" condition fails. After sleep when both the threads try to execute "static_subtract_instance_var" method still "x.num1==111" condition fails. So variable value remains 100.






    share|improve this answer























    • Hi @nuwan, thanks for your input. Yes, 100 I got is correct . But I am aiming to have a result of 89. I wanted to have an example where even there are synchronized methods (instance and static) in place, even with the checking of "x.num1==111", both methods still ran at the same time and both subtracted 11 at the same variable. And at the end variable result is 89.

      – jpibay
      Mar 27 at 5:50
















    1














    The result 100 you got is correct.
    thread1 and thread2 will run at the same time. Since "subtract_instance_var" method is synchronized one thread will make the variable 100. Then that thread will go to sleep. As the lock is released other thread can execute "subtract_instance_var". But nothing will happen as "x.num1==111" condition fails. After sleep when both the threads try to execute "static_subtract_instance_var" method still "x.num1==111" condition fails. So variable value remains 100.






    share|improve this answer























    • Hi @nuwan, thanks for your input. Yes, 100 I got is correct . But I am aiming to have a result of 89. I wanted to have an example where even there are synchronized methods (instance and static) in place, even with the checking of "x.num1==111", both methods still ran at the same time and both subtracted 11 at the same variable. And at the end variable result is 89.

      – jpibay
      Mar 27 at 5:50














    1












    1








    1







    The result 100 you got is correct.
    thread1 and thread2 will run at the same time. Since "subtract_instance_var" method is synchronized one thread will make the variable 100. Then that thread will go to sleep. As the lock is released other thread can execute "subtract_instance_var". But nothing will happen as "x.num1==111" condition fails. After sleep when both the threads try to execute "static_subtract_instance_var" method still "x.num1==111" condition fails. So variable value remains 100.






    share|improve this answer













    The result 100 you got is correct.
    thread1 and thread2 will run at the same time. Since "subtract_instance_var" method is synchronized one thread will make the variable 100. Then that thread will go to sleep. As the lock is released other thread can execute "subtract_instance_var". But nothing will happen as "x.num1==111" condition fails. After sleep when both the threads try to execute "static_subtract_instance_var" method still "x.num1==111" condition fails. So variable value remains 100.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 26 at 8:08









    nuwannuwan

    707 bronze badges




    707 bronze badges












    • Hi @nuwan, thanks for your input. Yes, 100 I got is correct . But I am aiming to have a result of 89. I wanted to have an example where even there are synchronized methods (instance and static) in place, even with the checking of "x.num1==111", both methods still ran at the same time and both subtracted 11 at the same variable. And at the end variable result is 89.

      – jpibay
      Mar 27 at 5:50


















    • Hi @nuwan, thanks for your input. Yes, 100 I got is correct . But I am aiming to have a result of 89. I wanted to have an example where even there are synchronized methods (instance and static) in place, even with the checking of "x.num1==111", both methods still ran at the same time and both subtracted 11 at the same variable. And at the end variable result is 89.

      – jpibay
      Mar 27 at 5:50

















    Hi @nuwan, thanks for your input. Yes, 100 I got is correct . But I am aiming to have a result of 89. I wanted to have an example where even there are synchronized methods (instance and static) in place, even with the checking of "x.num1==111", both methods still ran at the same time and both subtracted 11 at the same variable. And at the end variable result is 89.

    – jpibay
    Mar 27 at 5:50






    Hi @nuwan, thanks for your input. Yes, 100 I got is correct . But I am aiming to have a result of 89. I wanted to have an example where even there are synchronized methods (instance and static) in place, even with the checking of "x.num1==111", both methods still ran at the same time and both subtracted 11 at the same variable. And at the end variable result is 89.

    – jpibay
    Mar 27 at 5:50














    1














    Your example code does not execute the static substraction and the instance substraction at the same time. So no Thread-safety is engaged.



    Also,your code only substracts 11 if the original value is 111. So your result is 100.



    Here is an alternate main that will execute substract and static_substract in concurrency.



    public static void main(String args[]) 
    System.out.println("Program has started...");
    System.out.println("The value of the instance variable is:" + new Code147_class1().num1);
    System.out.println("The value of the static variable is:" + Code147_class1.num2);

    Code147 cd1 = new Code147();

    Thread thread1 = new Thread(() ->
    IntStream.range(0, 5).forEach(i->
    cd1.subtract_instance_var(cd1.z);
    );
    , "instance thread");
    Thread thread2 = new Thread(() ->
    IntStream.range(0, 5).forEach(i->
    static_subtract_instance_var(cd1.z);
    );
    , "static thread");

    thread1.start();
    thread2.start();

    // main


    Notice that in this code two threads substract 11, 5 times each, from the initial 111. The left over should be 1. It won't always be, because of thread safety.



    Complete code with thread safety problem



    import java.util.stream.IntStream;

    class Code147_class1
    int num1 = 111;

    // Code147_OK_class1

    public class Code147

    Code147_OK_class1 z = new Code147_OK_class1();

    public static void main(String args[])
    System.out.println("Program has started...");
    System.out.println("The value of the instance variable is:" + new Code147_OK_class1().num1);

    Code147 cd1 = new Code147();

    Thread thread1 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tInstance Substract 11 #" + (i + 1));
    cd1.subtract_instance_var(cd1.z);
    );
    , "instance thread");
    Thread thread2 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tStatic Substract 11 #" + (i + 1));
    static_subtract_instance_var(cd1.z);
    );
    , "static thread");

    thread1.start();
    thread2.start();

    // main

    public synchronized void subtract_instance_var(Code147_OK_class1 x)
    // if (x.num1 == 111)

    try
    Thread.sleep(100);
    catch (Exception ex)


    x.num1 = x.num1 - 11;
    System.out.println("Value is subtracted at thread T" + Thread.currentThread().getId());

    // // if

    System.out.println("The value of instance variable at the end for thread T" + Thread.currentThread().getId()
    + " is " + x.num1);

    // subtract_instance_var

    public synchronized static void static_subtract_instance_var(Code147_OK_class1 x)
    // if (x.num1 == 111)
    try
    Thread.sleep(100);
    catch (InterruptedException ex)
    // catch
    x.num1 = x.num1 - 11;
    System.out.println("STATIC Value is subtracted at thread T" + Thread.currentThread().getId());
    // // if

    System.out.println("STATIC The value of instance variable at the end for thread T"
    + Thread.currentThread().getId() + " is " + x.num1);

    // stati_subtract_var

    // class


    Example Output




    Program has started...
    The value of the instance variable is:111
    Instance Substract 11 #1
    Static Substract 11 #1
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 89
    Static Substract 11 #2
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 89
    Instance Substract 11 #2
    Value is subtracted at thread T10
    STATIC Value is subtracted at thread T11
    The value of instance variable at the end for thread T10 is 67
    Instance Substract 11 #3
    STATIC The value of instance variable at the end for thread T11 is 67
    Static Substract 11 #3
    STATIC Value is subtracted at thread T11
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 45
    Instance Substract 11 #4
    STATIC The value of instance variable at the end for thread T11 is 45
    Static Substract 11 #4
    Value is subtracted at thread T10
    STATIC Value is subtracted at thread T11
    The value of instance variable at the end for thread T10 is 23
    Instance Substract 11 #5
    STATIC The value of instance variable at the end for thread T11 is 23
    Static Substract 11 #5
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 12
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 12


    Notice the last value is 12, not 1...



    Complete code with thread safety fixed



    You could make your program thread safe by synchronizing on the same monitor, say z in this example :



    import java.util.stream.IntStream;

    class Code147_OK_class1
    int num1 = 111;

    // Code147_OK_class1

    public class Code148_OK

    Code147_class1 z = new Code147_class1();

    public static void main(String args[])
    System.out.println("Program has started...");
    System.out.println("The value of the instance variable is:" + new Code147_class1().num1);

    Code148_OK cd1 = new Code148_OK();

    Thread thread1 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tInstance Substract 11 #" + (i + 1));
    cd1.subtract_instance_var(cd1.z);
    );
    , "instance thread");
    Thread thread2 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tStatic Substract 11 #" + (i + 1));
    static_subtract_instance_var(cd1.z);
    );
    , "static thread");

    thread1.start();
    thread2.start();

    // main

    public /* synchronized */ void subtract_instance_var(Code147_class1 x)
    synchronized (x)
    // if (x.num1 == 111)

    try
    Thread.sleep(100);
    catch (Exception ex)


    x.num1 = x.num1 - 11;
    System.out.println("Value is subtracted at thread T" + Thread.currentThread().getId());

    // // if

    System.out.println("The value of instance variable at the end for thread T" + Thread.currentThread().getId()
    + " is " + x.num1);


    // subtract_instance_var

    public /* synchronized */ static void static_subtract_instance_var(Code147_class1 x)
    synchronized (x)
    // if (x.num1 == 111)
    try
    Thread.sleep(100);
    catch (InterruptedException ex)
    // catch
    x.num1 = x.num1 - 11;
    System.out.println("STATIC Value is subtracted at thread T" + Thread.currentThread().getId());
    // // if

    System.out.println("STATIC The value of instance variable at the end for thread T"
    + Thread.currentThread().getId() + " is " + x.num1);


    // stati_subtract_var

    // class


    Output




    Program has started...
    The value of the instance variable is:111
    Instance Substract 11 #1
    Static Substract 11 #1
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 100
    Instance Substract 11 #2
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 89
    Static Substract 11 #2
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 78
    Instance Substract 11 #3
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 67
    Static Substract 11 #3
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 56
    Instance Substract 11 #4
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 45
    Static Substract 11 #4
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 34
    Instance Substract 11 #5
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 23
    Static Substract 11 #5
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 12
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 1


    Tell me if the java 8 lambda stuff is unclear, I will rewrite it with "classic" Runnables and loops.



    HTH!






    share|improve this answer























    • Thank you so much @Highbrainer ! Your post helped me a lot. The key for me is that I didn't realize that you could actually specify what specific method to run for a runnable class when initiating a thread. (and also learning lambda expressions on the fly. I haven't yet learned that part from the book lol.) Actually came up with my own solution based on what is advised from the book. I will post it in here. Again Thanks!

      – jpibay
      Mar 27 at 5:31











    • Based on the book it is mentioned there: To keep things simple: in order to make a class thread-safe, methods that access changeable fields need to be synchronized. Access to static fields should be done from static synchronized methods. Access to non-static fields should be done from non-static synchronize method

      – jpibay
      Mar 27 at 5:35












    • Here is my solution:

      – jpibay
      Mar 27 at 5:38















    1














    Your example code does not execute the static substraction and the instance substraction at the same time. So no Thread-safety is engaged.



    Also,your code only substracts 11 if the original value is 111. So your result is 100.



    Here is an alternate main that will execute substract and static_substract in concurrency.



    public static void main(String args[]) 
    System.out.println("Program has started...");
    System.out.println("The value of the instance variable is:" + new Code147_class1().num1);
    System.out.println("The value of the static variable is:" + Code147_class1.num2);

    Code147 cd1 = new Code147();

    Thread thread1 = new Thread(() ->
    IntStream.range(0, 5).forEach(i->
    cd1.subtract_instance_var(cd1.z);
    );
    , "instance thread");
    Thread thread2 = new Thread(() ->
    IntStream.range(0, 5).forEach(i->
    static_subtract_instance_var(cd1.z);
    );
    , "static thread");

    thread1.start();
    thread2.start();

    // main


    Notice that in this code two threads substract 11, 5 times each, from the initial 111. The left over should be 1. It won't always be, because of thread safety.



    Complete code with thread safety problem



    import java.util.stream.IntStream;

    class Code147_class1
    int num1 = 111;

    // Code147_OK_class1

    public class Code147

    Code147_OK_class1 z = new Code147_OK_class1();

    public static void main(String args[])
    System.out.println("Program has started...");
    System.out.println("The value of the instance variable is:" + new Code147_OK_class1().num1);

    Code147 cd1 = new Code147();

    Thread thread1 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tInstance Substract 11 #" + (i + 1));
    cd1.subtract_instance_var(cd1.z);
    );
    , "instance thread");
    Thread thread2 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tStatic Substract 11 #" + (i + 1));
    static_subtract_instance_var(cd1.z);
    );
    , "static thread");

    thread1.start();
    thread2.start();

    // main

    public synchronized void subtract_instance_var(Code147_OK_class1 x)
    // if (x.num1 == 111)

    try
    Thread.sleep(100);
    catch (Exception ex)


    x.num1 = x.num1 - 11;
    System.out.println("Value is subtracted at thread T" + Thread.currentThread().getId());

    // // if

    System.out.println("The value of instance variable at the end for thread T" + Thread.currentThread().getId()
    + " is " + x.num1);

    // subtract_instance_var

    public synchronized static void static_subtract_instance_var(Code147_OK_class1 x)
    // if (x.num1 == 111)
    try
    Thread.sleep(100);
    catch (InterruptedException ex)
    // catch
    x.num1 = x.num1 - 11;
    System.out.println("STATIC Value is subtracted at thread T" + Thread.currentThread().getId());
    // // if

    System.out.println("STATIC The value of instance variable at the end for thread T"
    + Thread.currentThread().getId() + " is " + x.num1);

    // stati_subtract_var

    // class


    Example Output




    Program has started...
    The value of the instance variable is:111
    Instance Substract 11 #1
    Static Substract 11 #1
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 89
    Static Substract 11 #2
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 89
    Instance Substract 11 #2
    Value is subtracted at thread T10
    STATIC Value is subtracted at thread T11
    The value of instance variable at the end for thread T10 is 67
    Instance Substract 11 #3
    STATIC The value of instance variable at the end for thread T11 is 67
    Static Substract 11 #3
    STATIC Value is subtracted at thread T11
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 45
    Instance Substract 11 #4
    STATIC The value of instance variable at the end for thread T11 is 45
    Static Substract 11 #4
    Value is subtracted at thread T10
    STATIC Value is subtracted at thread T11
    The value of instance variable at the end for thread T10 is 23
    Instance Substract 11 #5
    STATIC The value of instance variable at the end for thread T11 is 23
    Static Substract 11 #5
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 12
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 12


    Notice the last value is 12, not 1...



    Complete code with thread safety fixed



    You could make your program thread safe by synchronizing on the same monitor, say z in this example :



    import java.util.stream.IntStream;

    class Code147_OK_class1
    int num1 = 111;

    // Code147_OK_class1

    public class Code148_OK

    Code147_class1 z = new Code147_class1();

    public static void main(String args[])
    System.out.println("Program has started...");
    System.out.println("The value of the instance variable is:" + new Code147_class1().num1);

    Code148_OK cd1 = new Code148_OK();

    Thread thread1 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tInstance Substract 11 #" + (i + 1));
    cd1.subtract_instance_var(cd1.z);
    );
    , "instance thread");
    Thread thread2 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tStatic Substract 11 #" + (i + 1));
    static_subtract_instance_var(cd1.z);
    );
    , "static thread");

    thread1.start();
    thread2.start();

    // main

    public /* synchronized */ void subtract_instance_var(Code147_class1 x)
    synchronized (x)
    // if (x.num1 == 111)

    try
    Thread.sleep(100);
    catch (Exception ex)


    x.num1 = x.num1 - 11;
    System.out.println("Value is subtracted at thread T" + Thread.currentThread().getId());

    // // if

    System.out.println("The value of instance variable at the end for thread T" + Thread.currentThread().getId()
    + " is " + x.num1);


    // subtract_instance_var

    public /* synchronized */ static void static_subtract_instance_var(Code147_class1 x)
    synchronized (x)
    // if (x.num1 == 111)
    try
    Thread.sleep(100);
    catch (InterruptedException ex)
    // catch
    x.num1 = x.num1 - 11;
    System.out.println("STATIC Value is subtracted at thread T" + Thread.currentThread().getId());
    // // if

    System.out.println("STATIC The value of instance variable at the end for thread T"
    + Thread.currentThread().getId() + " is " + x.num1);


    // stati_subtract_var

    // class


    Output




    Program has started...
    The value of the instance variable is:111
    Instance Substract 11 #1
    Static Substract 11 #1
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 100
    Instance Substract 11 #2
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 89
    Static Substract 11 #2
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 78
    Instance Substract 11 #3
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 67
    Static Substract 11 #3
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 56
    Instance Substract 11 #4
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 45
    Static Substract 11 #4
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 34
    Instance Substract 11 #5
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 23
    Static Substract 11 #5
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 12
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 1


    Tell me if the java 8 lambda stuff is unclear, I will rewrite it with "classic" Runnables and loops.



    HTH!






    share|improve this answer























    • Thank you so much @Highbrainer ! Your post helped me a lot. The key for me is that I didn't realize that you could actually specify what specific method to run for a runnable class when initiating a thread. (and also learning lambda expressions on the fly. I haven't yet learned that part from the book lol.) Actually came up with my own solution based on what is advised from the book. I will post it in here. Again Thanks!

      – jpibay
      Mar 27 at 5:31











    • Based on the book it is mentioned there: To keep things simple: in order to make a class thread-safe, methods that access changeable fields need to be synchronized. Access to static fields should be done from static synchronized methods. Access to non-static fields should be done from non-static synchronize method

      – jpibay
      Mar 27 at 5:35












    • Here is my solution:

      – jpibay
      Mar 27 at 5:38













    1












    1








    1







    Your example code does not execute the static substraction and the instance substraction at the same time. So no Thread-safety is engaged.



    Also,your code only substracts 11 if the original value is 111. So your result is 100.



    Here is an alternate main that will execute substract and static_substract in concurrency.



    public static void main(String args[]) 
    System.out.println("Program has started...");
    System.out.println("The value of the instance variable is:" + new Code147_class1().num1);
    System.out.println("The value of the static variable is:" + Code147_class1.num2);

    Code147 cd1 = new Code147();

    Thread thread1 = new Thread(() ->
    IntStream.range(0, 5).forEach(i->
    cd1.subtract_instance_var(cd1.z);
    );
    , "instance thread");
    Thread thread2 = new Thread(() ->
    IntStream.range(0, 5).forEach(i->
    static_subtract_instance_var(cd1.z);
    );
    , "static thread");

    thread1.start();
    thread2.start();

    // main


    Notice that in this code two threads substract 11, 5 times each, from the initial 111. The left over should be 1. It won't always be, because of thread safety.



    Complete code with thread safety problem



    import java.util.stream.IntStream;

    class Code147_class1
    int num1 = 111;

    // Code147_OK_class1

    public class Code147

    Code147_OK_class1 z = new Code147_OK_class1();

    public static void main(String args[])
    System.out.println("Program has started...");
    System.out.println("The value of the instance variable is:" + new Code147_OK_class1().num1);

    Code147 cd1 = new Code147();

    Thread thread1 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tInstance Substract 11 #" + (i + 1));
    cd1.subtract_instance_var(cd1.z);
    );
    , "instance thread");
    Thread thread2 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tStatic Substract 11 #" + (i + 1));
    static_subtract_instance_var(cd1.z);
    );
    , "static thread");

    thread1.start();
    thread2.start();

    // main

    public synchronized void subtract_instance_var(Code147_OK_class1 x)
    // if (x.num1 == 111)

    try
    Thread.sleep(100);
    catch (Exception ex)


    x.num1 = x.num1 - 11;
    System.out.println("Value is subtracted at thread T" + Thread.currentThread().getId());

    // // if

    System.out.println("The value of instance variable at the end for thread T" + Thread.currentThread().getId()
    + " is " + x.num1);

    // subtract_instance_var

    public synchronized static void static_subtract_instance_var(Code147_OK_class1 x)
    // if (x.num1 == 111)
    try
    Thread.sleep(100);
    catch (InterruptedException ex)
    // catch
    x.num1 = x.num1 - 11;
    System.out.println("STATIC Value is subtracted at thread T" + Thread.currentThread().getId());
    // // if

    System.out.println("STATIC The value of instance variable at the end for thread T"
    + Thread.currentThread().getId() + " is " + x.num1);

    // stati_subtract_var

    // class


    Example Output




    Program has started...
    The value of the instance variable is:111
    Instance Substract 11 #1
    Static Substract 11 #1
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 89
    Static Substract 11 #2
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 89
    Instance Substract 11 #2
    Value is subtracted at thread T10
    STATIC Value is subtracted at thread T11
    The value of instance variable at the end for thread T10 is 67
    Instance Substract 11 #3
    STATIC The value of instance variable at the end for thread T11 is 67
    Static Substract 11 #3
    STATIC Value is subtracted at thread T11
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 45
    Instance Substract 11 #4
    STATIC The value of instance variable at the end for thread T11 is 45
    Static Substract 11 #4
    Value is subtracted at thread T10
    STATIC Value is subtracted at thread T11
    The value of instance variable at the end for thread T10 is 23
    Instance Substract 11 #5
    STATIC The value of instance variable at the end for thread T11 is 23
    Static Substract 11 #5
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 12
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 12


    Notice the last value is 12, not 1...



    Complete code with thread safety fixed



    You could make your program thread safe by synchronizing on the same monitor, say z in this example :



    import java.util.stream.IntStream;

    class Code147_OK_class1
    int num1 = 111;

    // Code147_OK_class1

    public class Code148_OK

    Code147_class1 z = new Code147_class1();

    public static void main(String args[])
    System.out.println("Program has started...");
    System.out.println("The value of the instance variable is:" + new Code147_class1().num1);

    Code148_OK cd1 = new Code148_OK();

    Thread thread1 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tInstance Substract 11 #" + (i + 1));
    cd1.subtract_instance_var(cd1.z);
    );
    , "instance thread");
    Thread thread2 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tStatic Substract 11 #" + (i + 1));
    static_subtract_instance_var(cd1.z);
    );
    , "static thread");

    thread1.start();
    thread2.start();

    // main

    public /* synchronized */ void subtract_instance_var(Code147_class1 x)
    synchronized (x)
    // if (x.num1 == 111)

    try
    Thread.sleep(100);
    catch (Exception ex)


    x.num1 = x.num1 - 11;
    System.out.println("Value is subtracted at thread T" + Thread.currentThread().getId());

    // // if

    System.out.println("The value of instance variable at the end for thread T" + Thread.currentThread().getId()
    + " is " + x.num1);


    // subtract_instance_var

    public /* synchronized */ static void static_subtract_instance_var(Code147_class1 x)
    synchronized (x)
    // if (x.num1 == 111)
    try
    Thread.sleep(100);
    catch (InterruptedException ex)
    // catch
    x.num1 = x.num1 - 11;
    System.out.println("STATIC Value is subtracted at thread T" + Thread.currentThread().getId());
    // // if

    System.out.println("STATIC The value of instance variable at the end for thread T"
    + Thread.currentThread().getId() + " is " + x.num1);


    // stati_subtract_var

    // class


    Output




    Program has started...
    The value of the instance variable is:111
    Instance Substract 11 #1
    Static Substract 11 #1
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 100
    Instance Substract 11 #2
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 89
    Static Substract 11 #2
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 78
    Instance Substract 11 #3
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 67
    Static Substract 11 #3
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 56
    Instance Substract 11 #4
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 45
    Static Substract 11 #4
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 34
    Instance Substract 11 #5
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 23
    Static Substract 11 #5
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 12
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 1


    Tell me if the java 8 lambda stuff is unclear, I will rewrite it with "classic" Runnables and loops.



    HTH!






    share|improve this answer













    Your example code does not execute the static substraction and the instance substraction at the same time. So no Thread-safety is engaged.



    Also,your code only substracts 11 if the original value is 111. So your result is 100.



    Here is an alternate main that will execute substract and static_substract in concurrency.



    public static void main(String args[]) 
    System.out.println("Program has started...");
    System.out.println("The value of the instance variable is:" + new Code147_class1().num1);
    System.out.println("The value of the static variable is:" + Code147_class1.num2);

    Code147 cd1 = new Code147();

    Thread thread1 = new Thread(() ->
    IntStream.range(0, 5).forEach(i->
    cd1.subtract_instance_var(cd1.z);
    );
    , "instance thread");
    Thread thread2 = new Thread(() ->
    IntStream.range(0, 5).forEach(i->
    static_subtract_instance_var(cd1.z);
    );
    , "static thread");

    thread1.start();
    thread2.start();

    // main


    Notice that in this code two threads substract 11, 5 times each, from the initial 111. The left over should be 1. It won't always be, because of thread safety.



    Complete code with thread safety problem



    import java.util.stream.IntStream;

    class Code147_class1
    int num1 = 111;

    // Code147_OK_class1

    public class Code147

    Code147_OK_class1 z = new Code147_OK_class1();

    public static void main(String args[])
    System.out.println("Program has started...");
    System.out.println("The value of the instance variable is:" + new Code147_OK_class1().num1);

    Code147 cd1 = new Code147();

    Thread thread1 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tInstance Substract 11 #" + (i + 1));
    cd1.subtract_instance_var(cd1.z);
    );
    , "instance thread");
    Thread thread2 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tStatic Substract 11 #" + (i + 1));
    static_subtract_instance_var(cd1.z);
    );
    , "static thread");

    thread1.start();
    thread2.start();

    // main

    public synchronized void subtract_instance_var(Code147_OK_class1 x)
    // if (x.num1 == 111)

    try
    Thread.sleep(100);
    catch (Exception ex)


    x.num1 = x.num1 - 11;
    System.out.println("Value is subtracted at thread T" + Thread.currentThread().getId());

    // // if

    System.out.println("The value of instance variable at the end for thread T" + Thread.currentThread().getId()
    + " is " + x.num1);

    // subtract_instance_var

    public synchronized static void static_subtract_instance_var(Code147_OK_class1 x)
    // if (x.num1 == 111)
    try
    Thread.sleep(100);
    catch (InterruptedException ex)
    // catch
    x.num1 = x.num1 - 11;
    System.out.println("STATIC Value is subtracted at thread T" + Thread.currentThread().getId());
    // // if

    System.out.println("STATIC The value of instance variable at the end for thread T"
    + Thread.currentThread().getId() + " is " + x.num1);

    // stati_subtract_var

    // class


    Example Output




    Program has started...
    The value of the instance variable is:111
    Instance Substract 11 #1
    Static Substract 11 #1
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 89
    Static Substract 11 #2
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 89
    Instance Substract 11 #2
    Value is subtracted at thread T10
    STATIC Value is subtracted at thread T11
    The value of instance variable at the end for thread T10 is 67
    Instance Substract 11 #3
    STATIC The value of instance variable at the end for thread T11 is 67
    Static Substract 11 #3
    STATIC Value is subtracted at thread T11
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 45
    Instance Substract 11 #4
    STATIC The value of instance variable at the end for thread T11 is 45
    Static Substract 11 #4
    Value is subtracted at thread T10
    STATIC Value is subtracted at thread T11
    The value of instance variable at the end for thread T10 is 23
    Instance Substract 11 #5
    STATIC The value of instance variable at the end for thread T11 is 23
    Static Substract 11 #5
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 12
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 12


    Notice the last value is 12, not 1...



    Complete code with thread safety fixed



    You could make your program thread safe by synchronizing on the same monitor, say z in this example :



    import java.util.stream.IntStream;

    class Code147_OK_class1
    int num1 = 111;

    // Code147_OK_class1

    public class Code148_OK

    Code147_class1 z = new Code147_class1();

    public static void main(String args[])
    System.out.println("Program has started...");
    System.out.println("The value of the instance variable is:" + new Code147_class1().num1);

    Code148_OK cd1 = new Code148_OK();

    Thread thread1 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tInstance Substract 11 #" + (i + 1));
    cd1.subtract_instance_var(cd1.z);
    );
    , "instance thread");
    Thread thread2 = new Thread(() ->
    IntStream.range(0, 5).forEach(i ->
    System.out.println("tStatic Substract 11 #" + (i + 1));
    static_subtract_instance_var(cd1.z);
    );
    , "static thread");

    thread1.start();
    thread2.start();

    // main

    public /* synchronized */ void subtract_instance_var(Code147_class1 x)
    synchronized (x)
    // if (x.num1 == 111)

    try
    Thread.sleep(100);
    catch (Exception ex)


    x.num1 = x.num1 - 11;
    System.out.println("Value is subtracted at thread T" + Thread.currentThread().getId());

    // // if

    System.out.println("The value of instance variable at the end for thread T" + Thread.currentThread().getId()
    + " is " + x.num1);


    // subtract_instance_var

    public /* synchronized */ static void static_subtract_instance_var(Code147_class1 x)
    synchronized (x)
    // if (x.num1 == 111)
    try
    Thread.sleep(100);
    catch (InterruptedException ex)
    // catch
    x.num1 = x.num1 - 11;
    System.out.println("STATIC Value is subtracted at thread T" + Thread.currentThread().getId());
    // // if

    System.out.println("STATIC The value of instance variable at the end for thread T"
    + Thread.currentThread().getId() + " is " + x.num1);


    // stati_subtract_var

    // class


    Output




    Program has started...
    The value of the instance variable is:111
    Instance Substract 11 #1
    Static Substract 11 #1
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 100
    Instance Substract 11 #2
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 89
    Static Substract 11 #2
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 78
    Instance Substract 11 #3
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 67
    Static Substract 11 #3
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 56
    Instance Substract 11 #4
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 45
    Static Substract 11 #4
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 34
    Instance Substract 11 #5
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 23
    Static Substract 11 #5
    Value is subtracted at thread T10
    The value of instance variable at the end for thread T10 is 12
    STATIC Value is subtracted at thread T11
    STATIC The value of instance variable at the end for thread T11 is 1


    Tell me if the java 8 lambda stuff is unclear, I will rewrite it with "classic" Runnables and loops.



    HTH!







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 26 at 8:18









    HighbrainerHighbrainer

    6604 silver badges14 bronze badges




    6604 silver badges14 bronze badges












    • Thank you so much @Highbrainer ! Your post helped me a lot. The key for me is that I didn't realize that you could actually specify what specific method to run for a runnable class when initiating a thread. (and also learning lambda expressions on the fly. I haven't yet learned that part from the book lol.) Actually came up with my own solution based on what is advised from the book. I will post it in here. Again Thanks!

      – jpibay
      Mar 27 at 5:31











    • Based on the book it is mentioned there: To keep things simple: in order to make a class thread-safe, methods that access changeable fields need to be synchronized. Access to static fields should be done from static synchronized methods. Access to non-static fields should be done from non-static synchronize method

      – jpibay
      Mar 27 at 5:35












    • Here is my solution:

      – jpibay
      Mar 27 at 5:38

















    • Thank you so much @Highbrainer ! Your post helped me a lot. The key for me is that I didn't realize that you could actually specify what specific method to run for a runnable class when initiating a thread. (and also learning lambda expressions on the fly. I haven't yet learned that part from the book lol.) Actually came up with my own solution based on what is advised from the book. I will post it in here. Again Thanks!

      – jpibay
      Mar 27 at 5:31











    • Based on the book it is mentioned there: To keep things simple: in order to make a class thread-safe, methods that access changeable fields need to be synchronized. Access to static fields should be done from static synchronized methods. Access to non-static fields should be done from non-static synchronize method

      – jpibay
      Mar 27 at 5:35












    • Here is my solution:

      – jpibay
      Mar 27 at 5:38
















    Thank you so much @Highbrainer ! Your post helped me a lot. The key for me is that I didn't realize that you could actually specify what specific method to run for a runnable class when initiating a thread. (and also learning lambda expressions on the fly. I haven't yet learned that part from the book lol.) Actually came up with my own solution based on what is advised from the book. I will post it in here. Again Thanks!

    – jpibay
    Mar 27 at 5:31





    Thank you so much @Highbrainer ! Your post helped me a lot. The key for me is that I didn't realize that you could actually specify what specific method to run for a runnable class when initiating a thread. (and also learning lambda expressions on the fly. I haven't yet learned that part from the book lol.) Actually came up with my own solution based on what is advised from the book. I will post it in here. Again Thanks!

    – jpibay
    Mar 27 at 5:31













    Based on the book it is mentioned there: To keep things simple: in order to make a class thread-safe, methods that access changeable fields need to be synchronized. Access to static fields should be done from static synchronized methods. Access to non-static fields should be done from non-static synchronize method

    – jpibay
    Mar 27 at 5:35






    Based on the book it is mentioned there: To keep things simple: in order to make a class thread-safe, methods that access changeable fields need to be synchronized. Access to static fields should be done from static synchronized methods. Access to non-static fields should be done from non-static synchronize method

    – jpibay
    Mar 27 at 5:35














    Here is my solution:

    – jpibay
    Mar 27 at 5:38





    Here is my solution:

    – jpibay
    Mar 27 at 5:38











    0














    With inputs from @Highbrainer, I managed to get a program to run 2 threads with 1 running a synchronized instance method and another running a static method. Both modifying an instance field. As advised from the book, to prevent this kind of problem, we should always be modifying instance fields from an instance method and static fields from a s static method. I just modified the program to change the static method to an instance method.



    class code148_class1
    int num1 = 111;

    //code148_class1


    public class code148 implements Runnable

    static code148_class1 z = new code148_class1();

    public static void main (String args[])
    System.out.println("Program has started...");
    System.out.println("The value of the instance variable is:"+z.num1);

    code148 cd1 = new code148();

    Thread thread1 = new Thread(
    ()->
    cd1.subtract_instance_var(z);

    );
    Thread thread2 = new Thread(
    ()->
    cd1.NONstatic_subtract_instance_var(z);

    );

    thread1.start();
    thread2.start();


    //main

    public void run()
    System.out.println("Thread has started for:"+Thread.currentThread().getId());

    // try
    // subtract_instance_var(z);
    // Thread.sleep(100);
    // code148.static_subtract_instance_var(z);
    //
    // catch(Exception ex)
    //
    //
    //run

    public synchronized void subtract_instance_var(code148_class1 x)
    if(x.num1 ==111)

    try
    Thread.sleep(100);

    catch(Exception ex)


    x.num1 = x.num1 - 11;
    System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());

    //if

    System.out.println("The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

    //subtract_instance_var

    public synchronized void NONstatic_subtract_instance_var(code148_class1 x)
    if (x.num1==111)
    try
    Thread.sleep(100);

    catch(InterruptedException ex)
    //catch
    x.num1 = x.num1 -11;
    System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());
    //if

    System.out.println("STATIC The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

    //stati_subtract_var

    //class





    share|improve this answer



























      0














      With inputs from @Highbrainer, I managed to get a program to run 2 threads with 1 running a synchronized instance method and another running a static method. Both modifying an instance field. As advised from the book, to prevent this kind of problem, we should always be modifying instance fields from an instance method and static fields from a s static method. I just modified the program to change the static method to an instance method.



      class code148_class1
      int num1 = 111;

      //code148_class1


      public class code148 implements Runnable

      static code148_class1 z = new code148_class1();

      public static void main (String args[])
      System.out.println("Program has started...");
      System.out.println("The value of the instance variable is:"+z.num1);

      code148 cd1 = new code148();

      Thread thread1 = new Thread(
      ()->
      cd1.subtract_instance_var(z);

      );
      Thread thread2 = new Thread(
      ()->
      cd1.NONstatic_subtract_instance_var(z);

      );

      thread1.start();
      thread2.start();


      //main

      public void run()
      System.out.println("Thread has started for:"+Thread.currentThread().getId());

      // try
      // subtract_instance_var(z);
      // Thread.sleep(100);
      // code148.static_subtract_instance_var(z);
      //
      // catch(Exception ex)
      //
      //
      //run

      public synchronized void subtract_instance_var(code148_class1 x)
      if(x.num1 ==111)

      try
      Thread.sleep(100);

      catch(Exception ex)


      x.num1 = x.num1 - 11;
      System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());

      //if

      System.out.println("The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

      //subtract_instance_var

      public synchronized void NONstatic_subtract_instance_var(code148_class1 x)
      if (x.num1==111)
      try
      Thread.sleep(100);

      catch(InterruptedException ex)
      //catch
      x.num1 = x.num1 -11;
      System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());
      //if

      System.out.println("STATIC The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

      //stati_subtract_var

      //class





      share|improve this answer

























        0












        0








        0







        With inputs from @Highbrainer, I managed to get a program to run 2 threads with 1 running a synchronized instance method and another running a static method. Both modifying an instance field. As advised from the book, to prevent this kind of problem, we should always be modifying instance fields from an instance method and static fields from a s static method. I just modified the program to change the static method to an instance method.



        class code148_class1
        int num1 = 111;

        //code148_class1


        public class code148 implements Runnable

        static code148_class1 z = new code148_class1();

        public static void main (String args[])
        System.out.println("Program has started...");
        System.out.println("The value of the instance variable is:"+z.num1);

        code148 cd1 = new code148();

        Thread thread1 = new Thread(
        ()->
        cd1.subtract_instance_var(z);

        );
        Thread thread2 = new Thread(
        ()->
        cd1.NONstatic_subtract_instance_var(z);

        );

        thread1.start();
        thread2.start();


        //main

        public void run()
        System.out.println("Thread has started for:"+Thread.currentThread().getId());

        // try
        // subtract_instance_var(z);
        // Thread.sleep(100);
        // code148.static_subtract_instance_var(z);
        //
        // catch(Exception ex)
        //
        //
        //run

        public synchronized void subtract_instance_var(code148_class1 x)
        if(x.num1 ==111)

        try
        Thread.sleep(100);

        catch(Exception ex)


        x.num1 = x.num1 - 11;
        System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());

        //if

        System.out.println("The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

        //subtract_instance_var

        public synchronized void NONstatic_subtract_instance_var(code148_class1 x)
        if (x.num1==111)
        try
        Thread.sleep(100);

        catch(InterruptedException ex)
        //catch
        x.num1 = x.num1 -11;
        System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());
        //if

        System.out.println("STATIC The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

        //stati_subtract_var

        //class





        share|improve this answer













        With inputs from @Highbrainer, I managed to get a program to run 2 threads with 1 running a synchronized instance method and another running a static method. Both modifying an instance field. As advised from the book, to prevent this kind of problem, we should always be modifying instance fields from an instance method and static fields from a s static method. I just modified the program to change the static method to an instance method.



        class code148_class1
        int num1 = 111;

        //code148_class1


        public class code148 implements Runnable

        static code148_class1 z = new code148_class1();

        public static void main (String args[])
        System.out.println("Program has started...");
        System.out.println("The value of the instance variable is:"+z.num1);

        code148 cd1 = new code148();

        Thread thread1 = new Thread(
        ()->
        cd1.subtract_instance_var(z);

        );
        Thread thread2 = new Thread(
        ()->
        cd1.NONstatic_subtract_instance_var(z);

        );

        thread1.start();
        thread2.start();


        //main

        public void run()
        System.out.println("Thread has started for:"+Thread.currentThread().getId());

        // try
        // subtract_instance_var(z);
        // Thread.sleep(100);
        // code148.static_subtract_instance_var(z);
        //
        // catch(Exception ex)
        //
        //
        //run

        public synchronized void subtract_instance_var(code148_class1 x)
        if(x.num1 ==111)

        try
        Thread.sleep(100);

        catch(Exception ex)


        x.num1 = x.num1 - 11;
        System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());

        //if

        System.out.println("The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

        //subtract_instance_var

        public synchronized void NONstatic_subtract_instance_var(code148_class1 x)
        if (x.num1==111)
        try
        Thread.sleep(100);

        catch(InterruptedException ex)
        //catch
        x.num1 = x.num1 -11;
        System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());
        //if

        System.out.println("STATIC The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);

        //stati_subtract_var

        //class






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 27 at 5:47









        jpibayjpibay

        61 bronze badge




        61 bronze badge



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55351694%2fa-java-beginner-question-regarding-multi-threading%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해