问题:设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1,运行1000次(可以每个各执行250次也可自己计算只要总合1000),J初始为100,保证结果为100,写出程序
PS:这里主要用到了synchronized以及对象的wait和notify以及notifyAll方法
package com.test;
public class TestThread{
public static void main(String[] args) {
Operate o = new Operate();
IncreaseThread thread1 = new IncreaseThread(o);
IncreaseThread thread2 = new IncreaseThread(o);
DecreaseThread thread3 = new DecreaseThread(o);
DecreaseThread thread4 = new DecreaseThread(o);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
class Operate{
private int j=100;
private int count = 0;
public synchronized void increase(){
System.out.println("increase in");
while(100!=j){
try {
System.out.println(Thread.currentThread().getName()+"increase begin wait");
wait();
System.out.println(Thread.currentThread().getName()+"increase end wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
j++;
System.out.println("increase j:"+j);
count++;
System.out.println("increase count:"+count);
//切勿使用notify();只唤醒一个线程是不行的,因为有两个相同功能的线程会导致这2个线程都wait然后再通知到另外2个相同功能的线程又会2个线程都wait最终可能全部4个线程全部wait
notifyAll();
System.out.println("increase out");
}
public synchronized void decrease(){
System.out.println("decrease in");
while(100==j){
try {
System.out.println(Thread.currentThread().getName()+"decrease begin wait");
wait();
System.out.println(Thread.currentThread().getName()+"decrease end wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
j--;
System.out.println("decrease j:"+j);
count++;
System.out.println("decrease count:"+count);
//切勿使用notify();只唤醒一个线程是不行的,因为有两个相同功能的线程会导致这2个线程都wait然后再通知到另外2个相同功能的线程又会2个线程都wait最终可能全部4个线程全部wait
notifyAll();
System.out.println("decrease out");
}
}
class IncreaseThread extends Thread{
private Operate o;
public IncreaseThread(Operate o) {
this.o = o;
}
@Override
public void run() {
for(int i = 0;i<250;i++){
o.increase();
}
}
}
class DecreaseThread extends Thread{
private Operate o;
public DecreaseThread(Operate o) {
this.o = o;
}
@Override
public void run() {
for(int i = 0;i<250;i++){
o.decrease();
}
}
}