Multi thread + multi object + synchronized (example)
1) HasSelPrivateNum.java class
public class HasSelPrivateNum { private int num = 0; synchronized public void addI(String username) { try { if (username.equals("a")) { num = 100; System.out.println("a set over"); Thread.sleep(2000); } else { num = 200; System.out.println("b set over"); } System.out.println(username + " num=" + num); } catch (InterruptedException e) { e.printStackTrace(); } } }
(2)ThreadA.java
public class ThreadA extends Thread { private HasSelPrivateNum numRef; public ThreadA(HasSelPrivateNum numRef) { super(); this.numRef = numRef; } @Override public void run() { super.run(); numRef.addI("a"); } }
(3)ThreadB.java
public class ThreadB extends Thread { private HasSelPrivateNum numRef; public ThreadB(HasSelPrivateNum numRef) { super(); this.numRef = numRef; } @Override public void run() { super.run(); numRef.addI("b"); } }
(4)Run.java
public class Run { public static void main(String[] args) { //Notice here are two objects!!! HasSelPrivateNum numRef1 = new HasSelPrivateNum();//Object 1 HasSelPrivateNum numRef2 = new HasSelPrivateNum();//Object 2 ThreadA a = new ThreadA(numRef1); a.start(); ThreadB b = new ThreadB(numRef2); b.start(); } }
Operation result
summary
-
See that the running result is asynchronous. As mentioned earlier, the synchronized keyword is the object lock obtained. Here, two objects are created, so two locks are generated and executed separately, so there is no synchronization effect.
-
If it is the synchronized keyword plus the static keyword, the result is no longer an object lock, but a class lock!! The next article shows this situation: multithreading + single object + synchronized+static.