1、MyObject
public class MyObject {
private int counter;
public synchronized void increase(){
if (counter != 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
counter++;
System.out.print(counter);
notify();
}
public synchronized void decrease(){
if(counter == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
counter--;
System.out.print(counter);
notify();
}
}
2、IncreaseThread
public class IncreaseThread extends Thread {
private MyObject myObject;
public IncreaseThread(MyObject myObject) {
this.myObject = myObject;
}
@Override
public void run(){
for (int i = 0; i < 30; i++) {
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
myObject.increase();
}
}
}
3、DecreaseThread
public class DecreaseThread extends Thread {
private MyObject myObject;
public DecreaseThread(MyObject myObject) {
this.myObject = myObject;
}
@Override
public void run() {
for (int i = 0; i < 30; i++) {
try {
Thread.sleep((long)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
myObject.decrease();
}
}
}
4、测试类
public class MyTest {
public static void main(String [] args) {
MyObject myObject = new MyObject();
IncreaseThread increaseThread = new IncreaseThread(myObject);
DecreaseThread decreaseThread = new DecreaseThread(myObject);
increaseThread.start();
decreaseThread.start();
}
}
// 输出结果:
101010101010101010101010101010101010101010101010101010101010
5、扩展
如果两个增的线程,两个减的线程,需要将MyObject类中的方法,if判断改为while
本文通过一个具体的Java程序示例,介绍了如何使用synchronized关键字来实现线程间的同步操作,确保了线程安全。示例中包含了一个共享资源类MyObject及对应的增加和减少线程,演示了线程间等待和通知机制。
312

被折叠的 条评论
为什么被折叠?



