码迷,mamicode.com
首页 > 编程语言 > 详细

4样品线程,2在相同的数字加法器线程进一步2上相同的共享数字减影线程

时间:2015-10-14 17:26:56      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

package com.threeti.mecool.web;

//详细地址:减法的方法
public class AddJian {


public int i=0;

public synchronized void add(String threadName) {
i++;
System.out.println(threadName+"加法运算:"+i);
}

public synchronized void jian(String threadName) {
i--;
System.out.println(threadName+"减法运算:"+i);
}

}


package com.threeti.mecool.web;

//共享数据加10次线程
public class AddThread implements Runnable{
private AddJian addJian;
private String threadName;
public AddThread(AddJian addJian,String threadName){
this.addJian=addJian;
this.threadName=threadName;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
addJian.add(threadName);
}
}


}



package com.threeti.mecool.web;

//共享数据减10次线程
public class JianThread implements Runnable{
private AddJian addJian;
private String threadName;
public JianThread(AddJian addJian,String threadName){
this.addJian=addJian;
this.threadName=threadName;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
addJian.jian(threadName);
}
}


}


package com.threeti.mecool.web;


public class Test {


/**
* @param args
*/
public static void main(String[] args) {
      //同一个数字对象
      AddJian addJian=new AddJian();
      //2个线程对同一个数字加法运算
      Thread thread1=new Thread(new AddThread(addJian,"thread-01"));
      Thread thread2=new Thread(new AddThread(addJian,"thread-02"));
      thread1.start();
      thread2.start();
      
     //2个线程对同一个数字减法运算
      Thread thread3=new Thread(new JianThread(addJian,"thread-03"));
      Thread thread4=new Thread(new JianThread(addJian,"thread-04"));
      thread3.start();
      thread4.start();
}


}

版权声明:本文博主原创文章,博客,未经同意不得转载。

4样品线程,2在相同的数字加法器线程进一步2上相同的共享数字减影线程

标签:

原文地址:http://www.cnblogs.com/mengfanrong/p/4877827.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!