1.将目标对象,同步方法最为成员变量,成员方法
package com.sample.synchronizedThread;
class MultiThreadShareData1 {
private int j = 0;
public synchronized void increment() {
j++;
}
public synchronized void descrement() {
while (j < 0) {
try {
wait();
//continue;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notify();
}
class RunnableInner1 implements Runnable {
@Override
public void run() {
System.out.println("RunnableInner1 run before:"+j);
increment();
System.out.println("RunnableInner1 run after:"+j);
}
}
class RunnableInner2 implements Runnable {
@Override
public void run() {
System.out.println("RunnableInner2 run before:"+j);
descrement();
System.out.println("RunnableInner2 run after:"+j);
}
}
public void test(){
for(int i=0;i<5;i++){
new Thread( new RunnableInner2()).start();
new Thread( new RunnableInner1()).start();
}
}
public static void main(String[] args) {
MultiThreadShareData1 outClass = new MultiThreadShareData1();
outClass.test();
}
}
2.将目标对象,同步方法或者同步块封装在一个类中,并将它作为成员变量或者方法变量
package com.sample.synchronizedThread;
import java.util.ArrayList;
import java.util.List;
public class MultiThreadShareData2 {
private static final TwoShareData data1 = new TwoShareData();// 成员变量
public static void main(String[] args) {
// 局部变量 加上 final。也可以行得通。作为方法的局部变量。
// final TwoShareData data1 = new TwoShareData();
// Runnable 为 内部类。
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
//System.out.println("--- fetch egg before:" + data1.checkEggs());
data1.decrement();
//System.out.println("--- fetch after:" + data1.checkEggs());
}
}).start();
}
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
//System.out.println("++ put egg before:" + data1.checkEggs());
data1.increment();
//System.out.println("++ put egg after:" + data1.checkEggs());
}
}).start();
}
}
}
class TwoShareData {
List<Object> eggs = new ArrayList<Object>();
public synchronized void increment() {
while (eggs.size() > 0) {
checkEggs("I want to put an egg.");
try {
wait();
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
eggs.add(1);
System.out.println("Notfy another Thread fetch an egg.");
notify();// 唤醒阻塞队列的某线程到就绪队列
}
public synchronized void decrement() {
while (eggs.size() == 0) {
checkEggs("I want to fetch an egg.");
try {
wait();
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//eggs.clear();// 清空盘子
System.out.println("waitting put an egg by anther thread;");
notify();// 唤醒阻塞队列的某线程到就绪队列
}
public void checkEggs(String e) {
Object obj = "Now nothings.";
for(Object o : eggs){
obj = o;
}
System.out.println(e+">>>:" + obj);
}
}