您的位置:首页 > 大数据 > 人工智能

多线程通信的简单实践

2016-03-16 16:30 447 查看
一直觉得对多线程的理解不够深刻,今天抱以学习的心态写了一个多线程的简单示例,话不多说,直接上代码(高手请绕行,谢谢)

public class ThreadTest {
public static int num = 0;
public static void main(String[] args) {
final ThreadTest test = new ThreadTest();
for (int j = 0; j < 5; j++) {
new Thread(new Runnable() {
@Override
public void run() {
test.increase();
}
}).start();
}
for (int j = 0; j < 5; j++) {
new Thread(new Runnable() {
@Override
public void run() {
test.decrease();
}
}).start();
}
}
public synchronized void increase() {
try {
while(num != 0) {
wait();
System.out.println("increase wait 完毕");
}
num++;
System.out.println(num);
notifyAll();
System.out.println("increase notify");
Thread.sleep(new Random().nextInt(2000));
System.out.println("increase sleep完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void decrease() {
try {
while (num == 0) {
wait();
System.out.println("decrease wait 完毕");
}
num--;
System.out.println(num);
notifyAll();
System.out.println("decrease notify");
Thread.sleep(new Random().nextInt(2000));
System.out.println("decrease sleep完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

多个线程对同一变量加减(五个加,五个减),顺序不定,当变量值等于0时,减线程等待,当变量大于0时,加线程等待,以此达到变量值始终介于0和1之间
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息