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

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();
}


}

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

posted @ 2015-10-14 16:25  mengfanrong  阅读(172)  评论(0编辑  收藏  举报