设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。
2015-08-01 08:46
627 查看
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();
}
}
}
}
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();
}
}
}
}
相关文章推荐
- HDU 1232 畅通工程
- uva-133 - The Dole Queue
- MSTSC远程终端中一个实用小技巧
- 【CSS学习】CSS 表格
- 利用GEPHI做网页排名计算
- html页面里table导出为excel
- unity3d android开发初体验——远程安装调试篇
- HTTP 方法:GET 对比 POST
- iOS设计模式 - 装饰
- Android如何获取选择图片时的文件绝对路径方法
- jQuery动态添加删除select项(实现代码)
- UML读书笔记——01组件化设计
- spring实现java的邮件发送
- KNIMI数据挖掘建模与分析系列_004_利用KNIMI做客户流失预测
- 【android控件学习笔记】ListView
- [leetcode 32]Longest Valid Parentheses
- 请问什么是UTF字符串?
- Spring Data MongoDB 三:基本文档查询(Query、BasicQuery)(一)
- Quora 是如何维持高质量代码的
- 安全驾驶-预防爆胎(十)