Java concurrent programming instance (synchronized) and java concurrent programming instance
Here, we use a small program to illustrate that the logic is a counter (int I). The main logic function is that if resource I is monitored synchronously, no I value is output, however, if the keyword synchronized is not added, because it is executed concurrently by two threads, the I value will be output, and the class implements the Runnable interface.
The following is the run () method. I is used to add two at a time. If it is an odd number, it is output. If it is output (concurrent programming, shared resources are not monitored ), if there is no output (shared resources are monitored and only one thread is allowed at a time), the Run method of the Runnable interface is as follows:
public void run(){ while(true){ if(this.getValue()%2!=0){ System.out.println(this.getValue()); } if(Thread.currentThread().getName().equals("b")){ this.next(); } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Write a method to obtain the I value and add the I value respectively. If synchronized is required for the concurrent thread of synchronization monitoring, compare the result by yourself:
Public synchronized void next () {// synchronized, which defines the code block here and only allows one thread to access I ++ = 2; // I add two at a time} public synchronized int getValue () {return I;} // obtain the I value for output judgment
Create a main method in the class, construct an object, instantiate two threads, and add that the code block modified by the synchronized keyword can only be accessed by different threads of the same object at most once, if two objects are constructed, the synchronized modified code block will still be accessed at the same time, which may cause data confusion and deadlock.
The Code is as follows:
public static void main(String[] args){ SecondThread st = new SecondThread(); Thread st1 = new Thread(st,"a"); Thread st2 = new Thread(st,"b"); st1.start(); st2.start(); try { st1.join(); st1.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
The output is (no output, and the thread is not destroyed ):
If synchronized is removed, an odd number can be output.