One, if each thread executes the same code, you can use the same runnable to implement the shared
public class Multithreadsharedata {public
static void Main (string[] args) {
new Thread (New Sharedata ()). Start () ;
New Thread (New Sharedata ()). Start ();
Static class Sharedata implements runnable{
private int j =;
@Override public
synchronized void Run () {
j--}
}}
The two threads in the above code share data to implement the decrement operation of J variable, as the above code why to use a static inner class, the static role of this class is not dependent on an instance of the external class to create the object.
Two, if each thread executes different code, you need to use a different runnable object to implement the shared
public class Multithreadsharedata {public
static void Main (string[] args) {
final sharedata data1 = new Sharedata ();
Start the first thread
new Runnable () {
@Override public
void Run () {
data1.increment ();//Add
}
). Start ();
Start the second thread
new threads (new Runnable () {
@Override public
void Run () {
data1.decrement (); Minus
}
}). Start ();
Static class sharedata{
private int j = 0;
public synchronized void increment () {
j + +;
}
Public synchronized void Decrement () {
j--;
}
}
}
Modify the code above (to take the data as a member variable of the outer class and let the Runnable interface manipulate the member variable) as follows:
public class Multithreadsharedata {public static void main (string[] args) {Sharedata data1 = new ShareD
ATA ();
New Thread (New MyRunnable1 (DATA1)). Start ();
New Thread (New MyRunnable2 (DATA1)). Start ();
Static class MyRunnable1 implements runnable{private Sharedata data1;
Public MyRunnable1 (Sharedata data1) {this.data1 = data1;
@Override public void Run () {data1.increment (); } Static class MyRunnable2 implements runnable{private S
Haredata data1;
Public MyRunnable2 (Sharedata data2) {this.data1 = data1;
@Override public void Run () {data1.decrement ();
} static class sharedata{private int j = 0; public synchronized void IncremeNT () {j + +;
Public synchronized void Decrement () {j--; }
}
}
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/