Package com.example; Public class App { publicstaticvoid main (string[] args) { new dorunable (); New Thread (DR, "Thread1"); New Thread (DR, "Thread2"); T1.start (); T2.start (); }}
Packagecom.example; Public classDorunableImplementsRunnable {PrivateFoo foo =NewFoo (); @Override Public voidrun () { for(inti = 0; I < 4; i++) { This. foo.modify (10); Try{Thread.Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+"__"+ This. Foo.getnum ()); } } Public intGetnum () {return This. Foo.getnum (); }}
Packagecom.example; Public classFoo {Private intnum = 100; Public intGetnum () {return This. Num; } Public intModifyintN) {/*in the Java language, each object has a monitor that accesses the key parts of the code and prevents other objects from accessing the code (each object has a monitor that provides access to the mutex for key parts of the code). This key part is implemented using synchronized for methods or code annotations. At the same time in the same monitor, only one thread is allowed to run any critical part of the code. */ synchronized( This) {System.out.println ("In" + This. num + "" +N); intm = This. Num; This. num = M-N; System.out.println ("Out" + This. num + "" +N); } return This. Num; }}
Java Multithreading (synchronized)