设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1
2015-07-07 21:42
591 查看
Java代码
注:这里inc方法和dec方法加synchronized关键字是因为当两个线程同时操作同一个变量时,就算是简单的j++操作时,在系统底层也是通过多条机器语句来实现,所以在执行j++过程也是要耗费时间,这时就有可能在执行j++的时候,另外一个线程H就会对j进行操作,因此另外一个线程H可能操作的可能就不是最新的值了。因此要提供线程同步。
版本2:
本版本不需要synchronized,而用AtomicInteger代替
package com.yx.zzg; public class ThreadTest1 { private int j; public static void main(String args[]) { ThreadTest1 tt = new ThreadTest1(); Inc inc = tt.new Inc(); Dec dec = tt.new Dec(); for (int i = 0; i < 2; i++) { Thread t = new Thread(inc); t.start(); t = new Thread(dec); t.start(); } } private synchronized void inc() { j++; System.out.println(Thread.currentThread().getName() + "-inc:" + j); } private synchronized void dec() { j--; System.out.println(Thread.currentThread().getName() + "-dec:" + j); } class Inc implements Runnable { public void run() { for (int i = 0; i < 100; i++) { inc(); } } } class Dec implements Runnable { public void run() { for (int i = 0; i < 100; i++) { dec(); } } } }
注:这里inc方法和dec方法加synchronized关键字是因为当两个线程同时操作同一个变量时,就算是简单的j++操作时,在系统底层也是通过多条机器语句来实现,所以在执行j++过程也是要耗费时间,这时就有可能在执行j++的时候,另外一个线程H就会对j进行操作,因此另外一个线程H可能操作的可能就不是最新的值了。因此要提供线程同步。
版本2:
本版本不需要synchronized,而用AtomicInteger代替
package com.yx.zzg; public class ThreadTest1 { private AtomicInteger j=new AtomicInteger();public static void main(String args[]) { ThreadTest1 tt = new ThreadTest1(); Inc inc = tt.new Inc(); Dec dec = tt.new Dec(); for (int i = 0; i < 2; i++) { Thread t = new Thread(inc); t.start(); t = new Thread(dec); t.start(); } } private synchronized void inc() { j.incrementAndGet(); System.out.println(Thread.currentThread().getName() + "-inc:" + j); } private synchronized void dec() { j.decrementAndGet(); System.out.println(Thread.currentThread().getName() + "-dec:" + j); } class Inc implements Runnable { public void run() { for (int i = 0; i < 100; i++) { inc(); } } } class Dec implements Runnable { public void run() { for (int i = 0; i < 100; i++) { dec(); } } } }
相关文章推荐
- HTTP协议简介
- Java知多少(完结篇)
- 七月二号
- 破解TexturePacker加密资源 —— 使用IDA
- hdu 1719 Friend 数学推导
- OpenSSL windows 下编译
- 【学习笔记】【OC语言】第一个OC程序
- Implement Queue using Stacks
- 求三角形面积
- 学术牛人读外文文献
- 理解C++ dynamic_cast
- 人脸识别技术大总结—Face Detection & Alignment
- 判断主力强控盘股顶底的四个技巧
- Android 手机号码格式验证
- java集合 之 set 集合
- BibTex模板类型
- 七月一号
- 【Linux 内核网络协议栈源码剖析】数据包接收(含TCP协议状态变换)
- [刷题]N-Queens
- 《番茄工作法图解》第二章阅读笔记