多线程通信的简单实践
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之间
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之间
相关文章推荐
- Python3写爬虫(四)多线程实现数据爬取
- C#实现多线程的同步方法实例分析
- 浅谈chuck-lua中的多线程
- C#简单多线程同步和优先权用法实例
- C#多线程学习之(四)使用线程池进行多线程的自动管理
- C#多线程编程中的锁系统(三)
- 解析C#多线程编程中异步多线程的实现及线程池的使用
- C#多线程学习之(六)互斥对象用法实例
- 基于一个应用程序多线程误用的分析详解
- C#多线程学习之(三)生产者和消费者用法分析
- C#多线程学习之(一)多线程的相关概念分析
- C#多线程之Thread中Thread.IsAlive属性用法分析
- 分享我在工作中遇到的多线程下导致RCW无法释放的问题
- C#多线程编程之使用ReaderWriterLock类实现多用户读与单用户写同步的方法
- C#控制台下测试多线程的方法
- 21天学习android开发教程之SurfaceView与多线程的混搭
- Ruby 多线程的潜力和弱点分析
- C#中WPF使用多线程调用窗体组件的方法
- C#如何对多线程、多任务管理(demo)
- C#实现多线程的Web代理服务器实例