The data for custom threads can be shared or not shared, depending on how it is implemented.
1. Do not share the data multithreading implementation method:
Public classMyThreadextendsthread{Private intCount = 4; PublicMyThread (String threadname) { This. SetName (ThreadName); } @Override Public voidrun () { while(Count > 0) {Count= Count-1; System.out.println ("By" + Thread.CurrentThread (). GetName () + "calculation, Count =" +count); Try{Thread.Sleep (1000); }Catch(interruptedexception e) {e.printstacktrace (); } } } Public Static voidMain (string[] args) {MyThread Threada=NewMyThread ("A"); MyThread threadb=NewMyThread ("B"); MyThread THREADC=NewMyThread ("C"); Threada.start (); Threadb.start (); Threadc.start (); }}
The results of the implementation are as follows:
From the results, each thread is printed at 3, then 2, then 1, 0. It can be concluded that each thread has a copy of the variable count, which is not disturbed by other threads.
2. Multi-threaded implementation of shared data
Public classMyThreadextendsthread{Private intCount = 4; @Override Public voidrun () { while(Count > 0) {Count= Count-1; System.out.println ("By" + Thread.CurrentThread (). GetName () + "calculation, Count =" +count); Try{Thread.Sleep (1000); }Catch(interruptedexception e) {e.printstacktrace (); } } } Public Static voidMain (string[] args) {MyThread MyThread=NewMyThread (); Thread a=NewThread (MyThread, "A"); Thread b=NewThread (MyThread, "B"); Thread C=NewThread (MyThread, "C"); Thread D=NewThread (MyThread, "D"); A.start (); B.start (); C.start (); D.start (); }}
The results of the implementation are as follows:
As the result shows, a,b,c,d four threads share a variable count
Java Threading Summary (ii)