论坛首页 入门技术论坛

第一次编写的多线程程序,希望大家赐教

浏览 1419 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (9) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-10-31  
OO

//目的使用多线程实现计数功能
package com.thread.test;
//实现记数的类
public class AddCount {

public AddCount(){

}

public AddCount(Integer countNum ){
this.countNum = countNum;
}

private int countNum;

public int getCountNum() {
return countNum;
}

public void setCountNum(int countNum) {
this.countNum = countNum;
}

public void addNum(){
//countNum = countNum+1;
countNum +=1;
System.out.println("Off this method countnum : "+countNum);
System.out.println("Off this method threadname : "+Thread.currentThread().getName());
}
}

package com.thread.test;
//线程类
import com.thread.test.AddCount;

public class NumberThread implements Runnable {
private AddCount add  = new AddCount();
boolean flag =true;
public  void run() {
while(flag){
try{
synchronized(add){
System.out.println("Enter this method threadname : "+Thread.currentThread().getName());
System.out.println("Enter this method countNum : "+add.getCountNum());
add.addNum();
if(add.getCountNum()==100){
flag =false;
}
}
}catch(Exception e){
flag =false;
e.printStackTrace();
}
}
}

}

package com.thread.test;
//测试类
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import com.thread.test.NumberThread;

public class TestCount {

public static void main(String[] args) {


/**
* 没有使用线程池的调用方式
*/
/* NumberThread num = new NumberThread();
Thread td0 = new Thread(num);
td0.setName("td0");
td0.start();
Thread td1 = new Thread(num);
td1.setName("td1");
td1.start();*/
/**
* 使用线程池的调用方式
*/
ExecutorService exec=null;
NumberThread num;
try{
exec =Executors.newFixedThreadPool(2);
    num = new NumberThread();
Thread td0 = new Thread(num,"td0");
//td0.setName("td0");
exec.execute(td0);
Thread td1 = new Thread(num,"td1");
//td1.setName("td1");
exec.execute(td1);
}catch(Exception e){
e.printStackTrace();
}finally{
exec.shutdown();
}

}
}


论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics