楼主你好,cup的多线程指的是真正意义上的可以同时运行的线程数,各线程并行运行。但是Java中的并发线程指的是在一个进程中分时复用cpu的资源,只是在宏观上看来是同时运行的,两者是有区别的。理论上java最大的并发线程没有数量上的限制,但是开启一个线程是很耗系统资源的,如果并发量太大就会导致系统资源不足而死机,所以我们一般会用线程池的技术来控制线程的数量,也可以提高并发的效率,如果感兴趣,你可以看看线程池相关的资料。
方法如下:
首先
创建一个Bean用来存贮要得到的信
public class MonitorInfoBean {
/ 可使用内存 /
private long totalMemory;
/ 剩余内存 /
private long freeMemory;
/ 最大可使用内存 /
private long maxMemory;
/ *** 作系统 /
private String osName;
/ 总的物理内存 /
private long totalMemorySize;
/ 剩余的物理内存 /
private long freePhysicalMemorySize;
/ 已使用的物理内存 /
private long usedMemory;
/ 线程总数 /
private int totalThread;
/ cpu使用率 /
private double cpuRatio;
public long getFreeMemory() {
return freeMemory;
}
public void setFreeMemory(long freeMemory) {
thisfreeMemory = freeMemory;
}
public long getFreePhysicalMemorySize() {
return freePhysicalMemorySize;
}
public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {
thisfreePhysicalMemorySize = freePhysicalMemorySize;
}
public long getMaxMemory() {
return maxMemory;
}
public void setMaxMemory(long maxMemory) {
thismaxMemory = maxMemory;
}
public String getOsName() {
return osName;
}
public void setOsName(String osName) {
thisosName = osName;
}
public long getTotalMemory() {
return totalMemory;
}
public void setTotalMemory(long totalMemory) {
thistotalMemory = totalMemory;
}
public long getTotalMemorySize() {
return totalMemorySize;
}
public void setTotalMemorySize(long totalMemorySize) {
thistotalMemorySize = totalMemorySize;
}
public int getTotalThread() {
return totalThread;
}
public void setTotalThread(int totalThread) {
thistotalThread = totalThread;
}
public long getUsedMemory() {
return usedMemory;
}
public void setUsedMemory(long usedMemory) {
thisusedMemory = usedMemory;
}
public double getCpuRatio() {
return cpuRatio;
}
public void setCpuRatio(double cpuRatio) {
thiscpuRatio = cpuRatio;
}
}
之后,建立bean的接口
public interface IMonitorService {
public MonitorInfoBean getMonitorInfoBean() throws Exception;
}
然后,就是最关键的,得到cpu的利用率,已用内存,可用内存,最大内存等信息。
import javaioInputStreamReader;
import javaioLineNumberReader;
import sunmanagementManagementFactory;
import comsunmanagementOperatingSystemMXBean;
import javaio;
import javautilStringTokenizer;
/
获取系统信息的业务逻辑实现类
@author GuoHuang
/
public class MonitorServiceImpl implements IMonitorService {
private static final int CPUTIME = 30;
private static final int PERCENT = 100;
private static final int FAULTLENGTH = 10;
private static final File versionFile = new File("/proc/version");
private static String linuxVersion = null;
/
获得当前的监控对象
@return 返回构造好的监控对象
@throws Exception
@author GuoHuang
/
public MonitorInfoBean getMonitorInfoBean() throws Exception {
int kb = 1024;
// 可使用内存
long totalMemory = RuntimegetRuntime()totalMemory() / kb;
// 剩余内存
long freeMemory = RuntimegetRuntime()freeMemory() / kb;
// 最大可使用内存
long maxMemory = RuntimegetRuntime()maxMemory() / kb;
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
getOperatingSystemMXBean();
// *** 作系统
String osName = SystemgetProperty("osname");
// 总的物理内存
long totalMemorySize = osmxbgetTotalPhysicalMemorySize() / kb;
// 剩余的物理内存
long freePhysicalMemorySize = osmxbgetFreePhysicalMemorySize() / kb;
// 已使用的物理内存
long usedMemory = (osmxbgetTotalPhysicalMemorySize() - osmxb
getFreePhysicalMemorySize())
/ kb;
// 获得线程总数
ThreadGroup parentThread;
for (parentThread = ThreadcurrentThread()getThreadGroup(); parentThread
getParent() != null; parentThread = parentThreadgetParent())
;
int totalThread = parentThreadactiveCount();
double cpuRatio = 0;
if (osNametoLowerCase()startsWith("windows")) {
cpuRatio = thisgetCpuRatioForWindows();
}
else {
cpuRatio = thisgetCpuRateForLinux();
}
// 构造返回对象
MonitorInfoBean infoBean = new MonitorInfoBean();
infoBeansetFreeMemory(freeMemory);
infoBeansetFreePhysicalMemorySize(freePhysicalMemorySize);
infoBeansetMaxMemory(maxMemory);
infoBeansetOsName(osName);
infoBeansetTotalMemory(totalMemory);
infoBeansetTotalMemorySize(totalMemorySize);
infoBeansetTotalThread(totalThread);
infoBeansetUsedMemory(usedMemory);
infoBeansetCpuRatio(cpuRatio);
return infoBean;
}
private static double getCpuRateForLinux(){
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
StringTokenizer tokenStat = null;
try{
Systemoutprintln("Get usage rate of CUP , linux version: "+linuxVersion);
Process process = RuntimegetRuntime()exec("top -b -n 1");
is = processgetInputStream();
isr = new InputStreamReader(is);
brStat = new BufferedReader(isr);
if(linuxVersionequals("24")){
brStatreadLine();
brStatreadLine();
brStatreadLine();
brStatreadLine();
tokenStat = new StringTokenizer(brStatreadLine());
tokenStatnextToken();
tokenStatnextToken();
String user = tokenStatnextToken();
tokenStatnextToken();
String system = tokenStatnextToken();
tokenStatnextToken();
String nice = tokenStatnextToken();
Systemoutprintln(user+" , "+system+" , "+nice);
user = usersubstring(0,userindexOf("%"));
system = systemsubstring(0,systemindexOf("%"));
nice = nicesubstring(0,niceindexOf("%"));
float userUsage = new Float(user)floatValue();
float systemUsage = new Float(system)floatValue();
float niceUsage = new Float(nice)floatValue();
return (userUsage+systemUsage+niceUsage)/100;
}else{
brStatreadLine();
brStatreadLine();
tokenStat = new StringTokenizer(brStatreadLine());
tokenStatnextToken();
tokenStatnextToken();
tokenStatnextToken();
tokenStatnextToken();
tokenStatnextToken();
tokenStatnextToken();
tokenStatnextToken();
String cpuUsage = tokenStatnextToken();
Systemoutprintln("CPU idle : "+cpuUsage);
Float usage = new Float(cpuUsagesubstring(0,cpuUsageindexOf("%")));
return (1-usagefloatValue()/100);
}
} catch(IOException ioe){
Systemoutprintln(ioegetMessage());
freeResource(is, isr, brStat);
return 1;
} finally{
freeResource(is, isr, brStat);
}
}
new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, milliseconds,runnableTaskQueue, handler);
参数:
corePoolSize(线程池的基本大小):当提交一个任务到线程池时,线程池会创建一个线程来执行任务,即使其他空闲的基本线程能够执行新任务也会创建线程,等到需要执行的任务数大于线程池基本大小时就不再创建。如果调用了线程池的prestartAllCoreThreads方法,线程池会提前创建并启动所有基本线程。
runnableTaskQueue(任务队列):用于保存等待执行的任务的阻塞队列。 可以选择以下几个阻塞队列。
ArrayBlockingQueue:是一个基于数组结构的有界阻塞队列,此队列按 FIFO(先进先出)原则对元素进行排序。
LinkedBlockingQueue:一个基于链表结构的阻塞队列,此队列按FIFO (先进先出) 排序元素,吞吐量通常要高于ArrayBlockingQueue。静态工厂方法ExecutorsnewFixedThreadPool()使用了这个队列。
SynchronousQueue:一个不存储元素的阻塞队列。每个插入 *** 作必须等到另一个线程调用移除 *** 作,否则插入 *** 作一直处于阻塞状态,吞吐量通常要高于LinkedBlockingQueue,静态工厂方法ExecutorsnewCachedThreadPool使用了这个队列。
PriorityBlockingQueue:一个具有优先级的无限阻塞队列。
maximumPoolSize(线程池最大大小):线程池允许创建的最大线程数。如果队列满了,并且已创建的线程数小于最大线程数,则线程池会再创建新的线程执行任务。值得注意的是如果使用了无界的任务队列这个参数就没什么效果。
ThreadFactory:用于设置创建线程的工厂,可以通过线程工厂给每个创建出来的线程设置更有意义的名字。
RejectedExecutionHandler(饱和策略):当队列和线程池都满了,说明线程池处于饱和状态,那么必须采取一种策略处理提交的新任务。这个策略默认情况下是AbortPolicy,表示无法处理新任务时抛出异常。以下是JDK15提供的四种策略。
AbortPolicy:直接抛出异常。
CallerRunsPolicy:只用调用者所在线程来运行任务。
DiscardOldestPolicy:丢弃队列里最近的一个任务,并执行当前任务。
DiscardPolicy:不处理,丢弃掉。
当然也可以根据应用场景需要来实现RejectedExecutionHandler接口自定义策略。如记录日志或持久化不能处理的任务。
keepAliveTime(线程活动保持时间):线程池的工作线程空闲后,保持存活的时间。所以如果任务很多,并且每个任务执行的时间比较短,可以调大这个时间,提高线程的利用率。
TimeUnit(线程活动保持时间的单位):可选的单位有天(DAYS),小时(HOURS),分钟(MINUTES),毫秒(MILLISECONDS),微秒(MICROSECONDS, 千分之一毫秒)和毫微秒(NANOSECONDS, 千分之一微秒)。
线程池通俗的描述就是预先创建若干空闲线程 等到需要用多线程去处理事务的时候去唤醒某些空闲线程执行处理任务 这样就省去了频繁创建线程的时间 因为频 繁创建线程是要耗费大量的CPU资源的 如果一个应用程序需要频繁地处理大量并发事务 不断的创建销毁线程往往会大大地降低系统的效率 这时候线程池就派 上用场了
本文旨在使用Java语言编写一个通用的线程池 当需要使用线程池处理事务时 只需按照指定规范封装好事务处理对象 然后用已有的线程池对象去自动选择空 闲线程自动调用事务处理对象即可 并实现线程池的动态修改(修改当前线程数 最大线程数等) 下面是实现代码
//ThreadTask java
package polarman threadpool;
/ //
线程任务
@author ryang
/
public interface ThreadTask {
public void run();
}
//PooledThread java
package polarman threadpool;
import java util Collection; import java util Vector;
/ //
接受线程池管理的线程
@author ryang
/
public class PooledThread extends Thread {
protected Vector tasks = new Vector();
protected boolean running = false;
protected boolean stopped = false;
protected boolean paused = false;
protected boolean killed = false;
private ThreadPool pool;
public PooledThread(ThreadPool pool) { this pool = pool;
}
public void putTask(ThreadTask task) { tasks add(task);
}
public void putTasks(ThreadTask[] tasks) { for(int i= ; i<tasks length; i++) this tasks add(tasks[i]);
}
public void putTasks(Collection tasks) { this tasks addAll(tasks);
}
protected ThreadTask popTask() { if(tasks size() > ) return (ThreadTask)tasks remove( );
else
return null;
}
public boolean isRunning() {
return running;
}
public void stopTasks() {
stopped = true;
}
public void stopTasksSync() {
stopTasks();
while(isRunning()) { try {
sleep( );
} catch (InterruptedException e) {
}
}
}
public void pauseTasks() {
paused = true;
}
public void pauseTasksSync() {
pauseTasks();
while(isRunning()) { try {
sleep( );
} catch (InterruptedException e) {
}
}
}
public void kill() { if(!running)
interrupt();
else
killed = true;
}
public void killSync() {
kill();
while(isAlive()) { try {
sleep( );
} catch (InterruptedException e) {
}
}
}
public synchronized void startTasks() {
running = true;
this notify();
}
public synchronized void run() { try { while(true) { if(!running || tasks size() == ) { pool notifyForIdleThread(); //System out println(Thread currentThread() getId() + : 空闲 ); this wait(); }else {
ThreadTask task;
while((task = popTask()) != null) { task run(); if(stopped) {
stopped = false;
if(tasks size() > ) { tasks clear(); System out println(Thread currentThread() getId() + : Tasks are stopped );
break;
}
}
if(paused) {
paused = false;
if(tasks size() > ) { System out println(Thread currentThread() getId() + : Tasks are paused );
break;
}
}
}
running = false;
}
if(killed) {
killed = false;
break;
}
}
}catch(InterruptedException e) {
return;
}
//System out println(Thread currentThread() getId() + : Killed );
}
}
//ThreadPool java
package polarman threadpool;
import java util Collection; import java util Iterator; import java util Vector;
/ //
线程池
@author ryang
/
public class ThreadPool {
protected int maxPoolSize;
protected int initPoolSize;
protected Vector threads = new Vector();
protected boolean initialized = false;
protected boolean hasIdleThread = false;
public ThreadPool(int maxPoolSize int initPoolSize) { this maxPoolSize = maxPoolSize; this initPoolSize = initPoolSize;
}
public void init() {
initialized = true;
for(int i= ; i<initPoolSize; i++) {
PooledThread thread = new PooledThread(this);
thread start(); threads add(thread);
}
//System out println( 线程池初始化结束 线程数= + threads size() + 最大线程数= + maxPoolSize);
}
public void setMaxPoolSize(int maxPoolSize) { //System out println( 重设最大线程数 最大线程数= + maxPoolSize); this maxPoolSize = maxPoolSize;
if(maxPoolSize < getPoolSize())
setPoolSize(maxPoolSize);
}
/ //
重设当前线程数
若需杀掉某线程 线程不会立刻杀掉 而会等到线程中的事务处理完成 但此方法会立刻从线程池中移除该线程 不会等待事务处理结束
@param size
/
public void setPoolSize(int size) { if(!initialized) {
initPoolSize = size;
return;
}else if(size > getPoolSize()) { for(int i=getPoolSize(); i<size && i<maxPoolSize; i++) {
PooledThread thread = new PooledThread(this);
thread start(); threads add(thread);
}
}else if(size < getPoolSize()) { while(getPoolSize() > size) { PooledThread th = (PooledThread)threads remove( ); th kill();
}
}
//System out println( 重设线程数 线程数= + threads size());
}
public int getPoolSize() { return threads size();
}
protected void notifyForIdleThread() {
hasIdleThread = true;
}
protected boolean waitForIdleThread() {
hasIdleThread = false;
while(!hasIdleThread && getPoolSize() >= maxPoolSize) { try { Thread sleep( ); } catch (InterruptedException e) {
return false;
}
}
return true;
}
public synchronized PooledThread getIdleThread() { while(true) { for(Iterator itr=erator(); itr hasNext();) { PooledThread th = (PooledThread)itr next(); if(!th isRunning())
return th;
}
if(getPoolSize() < maxPoolSize) {
PooledThread thread = new PooledThread(this);
thread start(); threads add(thread);
return thread;
}
//System out println( 线程池已满 等待 );
if(waitForIdleThread() == false)
return null;
}
}
public void processTask(ThreadTask task) {
PooledThread th = getIdleThread();
if(th != null) { th putTask(task); th startTasks();
}
}
public void processTasksInSingleThread(ThreadTask[] tasks) {
PooledThread th = getIdleThread();
if(th != null) { th putTasks(tasks); th startTasks();
}
}
public void processTasksInSingleThread(Collection tasks) {
PooledThread th = getIdleThread();
if(th != null) { th putTasks(tasks); th startTasks();
}
}
}
下面是线程池的测试程序
//ThreadPoolTest java
import java io BufferedReader; import java io IOException; import java io InputStreamReader;
import polarman threadpool ThreadPool; import polarman threadpool ThreadTask;
public class ThreadPoolTest {
public static void main(String[] args) { System out println( quit 退出 ); System out println( task A 启动任务A 时长为 秒 ); System out println( size 设置当前线程池大小为 ); System out println( max 设置线程池最大线程数为 ); System out println();
final ThreadPool pool = new ThreadPool( ); pool init();
Thread cmdThread = new Thread() { public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System in));
while(true) { try { String line = reader readLine(); String words[] = line split( ); if(words[ ] equalsIgnoreCase( quit )) { System exit( ); }else if(words[ ] equalsIgnoreCase( size ) && words length >= ) { try { int size = Integer parseInt(words[ ]); pool setPoolSize(size); }catch(Exception e) {
}
}else if(words[ ] equalsIgnoreCase( max ) && words length >= ) { try { int max = Integer parseInt(words[ ]); pool setMaxPoolSize(max); }catch(Exception e) {
}
}else if(words[ ] equalsIgnoreCase( task ) && words length >= ) { try { int timelen = Integer parseInt(words[ ]); SimpleTask task = new SimpleTask(words[ ] timelen ); pool processTask(task); }catch(Exception e) {
}
}
} catch (IOException e) { e printStackTrace();
}
}
}
};
cmdThread start();
///
for(int i= ; i< ; i++){
SimpleTask task = new SimpleTask( Task + i (i+ ) ); pool processTask(task);
}/
}
}
class SimpleTask implements ThreadTask {
private String taskName;
private int timeLen;
public SimpleTask(String taskName int timeLen) { this taskName = taskName; this timeLen = timeLen;
}
public void run() { System out println(Thread currentThread() getId() +
: START TASK + taskName + );
try { Thread sleep(timeLen); } catch (InterruptedException e) {
}
System out println(Thread currentThread() getId() +
: END TASK + taskName + );
}
}
使用此线程池相当简单 下面两行代码初始化线程池
ThreadPool pool = new ThreadPool( ); pool init();
要处理的任务实现ThreadTask 接口即可(如测试代码里的SimpleTask) 这个接口只有一个方法run()
两行代码即可调用
lishixinzhi/Article/program/Java/hx/201311/27203
ExecutorService是个接口,如果你是用Executors静态方法生产的实例,见具体实现。
比如:
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnitMILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
那它是ThreadPoolExecutor的实例,你可以看它的方法,如getActiveCount(),getPoolSize()等。
以上就是关于java系统最大并发线程数大概是多少全部的内容,包括:java系统最大并发线程数大概是多少、如何获取java程序当前的使用内存、java如何确定线程池最多线程的大小等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)