- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个java代码(非常古老的遗留代码),它创建了许多线程。当进程运行时,一些线程被杀死而没有任何痕迹。看了代码,感觉异常处理很到位。但我不确定为什么有些线程被杀死。这个论坛中的任何专家都可以帮助我这个类是否缺少有关线程处理的任何内容吗?
代码如下:
public class WorkerGroup {
// This value shows the number of all none-idleling workers.
private volatile int m_numbersOfActiveWorkingWorkers = 0;
// This value is set by when a single worker wants to starve multi workers
private volatile int m_starveRequests = 0;
// Thread group
// Java Collection of all workers.
protected static ThreadGroup s_workGroup = null;
// Queue manager
// Work group name
private final String m_workGroupName;
// Shut Down process which is hooked onto termination process of the
// application.
private static FtpWorkerShutdownHook s_shutDownHook = null;
private final Log m_log = Log.create(WorkerGroup.class);
/**
* CTOR WorkerGroup and collector of workers
* @param workGroupName will name the workGroup
* @param manager Queue manager
*/
public WorkerGroup(final String workGroupName) {
super();
m_workGroupName = workGroupName;
if (s_shutDownHook == null) {
s_shutDownHook = new FtpWorkerShutdownHook();
Runtime.getRuntime().addShutdownHook(s_shutDownHook);
}
}
/**
* Start procedure to start all workers. This function can only be called
* once.
* @param numberOfWorkers The number of available workers for this group
*/
public void startWorkers(int numberOfWorkers) {
// can not use negative count
if (numberOfWorkers < 0) {
return;
}
// workgroup is assigned alread. Run once only.
if (s_workGroup != null) {
return;
}
// creation of the working group. All workers and the work group are
// set to be deamon threads. This will keep the main process alive until
// all workers are terminated.
s_workGroup = new ThreadGroup("Workers of " + m_workGroupName);
s_workGroup.setDaemon(true);
// maximize number of workers
if (numberOfWorkers > 16) {
numberOfWorkers = 16;
}
// create and start all workers.
for (int i = 0; i < numberOfWorkers; i++) {
startWorker("FtpWorker" + String.valueOf(i + 1));
}
}
// public void startWorker(final String workerName, final ITaskActions task) {
// final FtpWorker worker = new FtpWorker(workerName, this);
// worker.setDaemon(true);
// worker.start();
// }
public void startWorker(final String workerName) {
final FtpWorker worker = new FtpWorker(workerName, this);
worker.setDaemon(true);
worker.start();
}
/**
* Explicit shutdown procedure. The normal case is to kill the process
*/
public void shutDown() {
final Thread thread = new FtpWorkerShutdownHook();
thread.start();
try {
thread.join();
m_log.event("ftp work group shutdown thread terminated");
// LogAgent
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Returns the number of running (non terminated) threads assinged the the
* thread group
* @return Number of active threads
*/
protected int activeCount() {
if (s_workGroup == null) {
return 0;
}
else {
synchronized (s_workGroup) {
final int count = s_workGroup.activeCount();
// LogAgent.event("work group", "active count" + count + " active "
// + m_numbersOfActiveWorkingWorkers);
return count;
}
}
}
/**
* This function returns if the worker group is active This function may be
* overriden.
*
* @return True if there is workers available and/or
*/
public synchronized boolean runnable() {
return activeCount() > 0;
}
// **************************************************************************
// Mutex operation
// **************************************************************************
private final Mutex m_mutex = new Mutex();
public synchronized void incrementRunningWorkers() {
if (m_numbersOfActiveWorkingWorkers == 0) {
try {
m_mutex.acquire();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
++m_numbersOfActiveWorkingWorkers;
}
public synchronized void decrementRunningWorkers() {
--m_numbersOfActiveWorkingWorkers;
if (m_numbersOfActiveWorkingWorkers == 0) {
m_mutex.release();
}
}
protected void incrementStarveRequest() {
synchronized (m_mutex) {
m_starveRequests++;
}
}
protected void decrementStarveRequest() {
synchronized (m_mutex) {
m_starveRequests--;
}
}
public void acquire() {
try {
synchronized (m_mutex) {
m_mutex.acquire();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public void release() {
synchronized (m_mutex) {
m_mutex.release();
}
}
// --------------------------------------------------------------------------
// Basic Test getter methods
// --------------------------------------------------------------------------
protected final int getWorkingWorkersCount() {
return m_numbersOfActiveWorkingWorkers;
}
protected final boolean workersIsStarving() {
return m_starveRequests != 0;
}
}
Ftpworker 类是:
public class FtpWorker extends Thread{
// This instance will use log facility for debug and for CIF log.
private final Log m_log = Log.create(FtpWorker.class);
// pointer to onwer of this worker
protected FtpWorkerGroup m_workerGroup = null;
// setting m_running to false cause worker to terminate
protected boolean m_running = true;
private static boolean isRetryList = false;
// default sleeping time in mSec
protected int m_workerSleep = 2000;
protected EAServer m_eaServer = EAServer.createInstance();
private final NeHandler m_neManager = NeHandler.getHandler();
protected List<String> fileNotf = new Vector<String>();
protected List<String> retrylist = Collections.synchronizedList(new ArrayList<String>());
public FtpWorker(final String name, final FtpWorkerGroup workerGroup) {
super(FtpWorkerGroup.s_workGroup,name);
}
public void run() {
idle();
shutDownEvent();
}
private String getTask() {
String notification=null;
String nename;
NeInfo ne=null;
int delim;
if(retrylist.size()>0){
m_log.trace("============ RETRY LIST===== " + Thread.currentThread().getName());
m_log.trace("RETRY LIST ::" + retrylist ) ;
if((retrylist.isEmpty())){
m_log.trace("RETRY LIST IS EMPTY ");
return null;
}
notification= retrylist.remove(0);
m_log.trace("Thread :: " + Thread.currentThread().getName() + " scanning list for Notification[RETRY] :: " + notification );
delim = notification.indexOf("$");
nename= notification.substring(0, delim);
try {
ne = m_neManager.getNetworkElement(nename);
}catch (NeNotFoundException e1) {
m_log.critical("Unable to get properties for Network Elemenet "
+ nename + " Reason: " + e1.getMessage()+ "The Network Element is of Unsupported Version");
}
if((ne.getValidState()== NeInfo.NE_IS_STOPPED ) || (ne.getValidState()== NeInfo.NE_IS_STOPPING)){
if((retrylist.isEmpty())){
m_log.trace("RETRY LIST IS EMPTY ");
FtpWorker.isRetryList = false;
return null;
}
else{
int size = retrylist.size();
for(Iterator it = retrylist.iterator();it.hasNext(); ){
String test = (String)it.next();
// m_log.trace(" RETRY LIST files to be deleted, test is "+test );
if(test.contains(ne.getName())){
//retrylist.remove(test);
it.remove();
m_log.trace("file"+ test+ "is deleted from list");
m_log.trace(" NEW RETRY LIST FILE NOTIFICATION LIST ::" + retrylist ) ;
}
}
if((retrylist.isEmpty())){
m_log.trace("RETRY LIST IS EMPTY ");
FtpWorker.isRetryList = false;
}
return null;
}
}
if(!ne.getisInFtp()){
m_log.trace("FTP Not Set[RETRY] " +notification);
ne.setisInFtp();
m_log.trace("FETCH FILE USING NOTIFICATION[RETRY] " +notification);
FtpWorker.isRetryList = false;
m_log.trace("============Returning from RETRY LIST===== " + Thread.currentThread().getName());
return notification;
}
else{
m_log.trace("FTP Set. ADDING NOTIFICATION BACK TO RETRY QUEUE:::: " +notification);
FtpWorker.isRetryList = true;
retrylist.add(notification);
m_log.trace("============Returning NULL RETRY LIST===== " + Thread.currentThread().getName());
return null;
}
}
if(EAServer.fileNotification!=null && (EAServer.fileNotification.size())>0 && !(isRetryList) ){
m_log.trace("====ORIGINAL FILE NOTIFICATION LIST== " + Thread.currentThread().getName());
try{
m_log.trace("ORIGINAL FILE NOTIFICATION LIST ::" + EAServer.fileNotification + " for Thread " + Thread.currentThread().getName()) ;
if((EAServer.fileNotification.isEmpty())){
m_log.trace("ORIGINAL LIST IS EMPTY ");
return null;
}
notification = (String)EAServer.fileNotification.remove(0);
m_log.trace("Thread :: " + Thread.currentThread().getName() + " scanning list for Notification[ORIGINAL] :: " + notification );
delim = notification.indexOf("$");
nename= notification.substring(0, delim);
m_log.trace("NOTIFICATION FOUND ::: " +notification);
try {
ne = m_neManager.getNetworkElement(nename);
}catch (NeNotFoundException e1) {
m_log.critical("Unable to get properties for Network Elemenet "
+ nename + " Reason: " + e1.getMessage()+ "The Network Element is of Unsupported Version");
}
}catch(Exception e){
m_log.trace("Exception caught while reading fileNotification " + e.getMessage() + " for Thread " + Thread.currentThread().getName());
return null;
}
if((ne.getValidState()== NeInfo.NE_IS_STOPPED ) || (ne.getValidState()== NeInfo.NE_IS_STOPPING)){
try {
ne.setisNotInFtp();
ne.deleteFileWithoutCollecting(ne.getFilePath());
ne.setValidState(NeInfo.NE_IS_STOPPED);
}
catch (CDMException e) {
m_log.trace("Could not delete file for " + ne.getName()
+ " because " + e.getMessage());
}
if((EAServer.fileNotification.isEmpty())){
m_log.trace("ORIGINAL LIST IS EMPTY NOW");
return null;
}
else{
try {
m_log.trace(" DELETING for NE Since Node is Stopped "+ ne.getName());
int size = EAServer.fileNotification.size();
m_log.trace("Size of ORIGINAL NOTIFICATION LIST " + size);
for(Iterator it = EAServer.fileNotification.iterator();it.hasNext(); ){
String test = (String)it.next();
if(test.contains(ne.getName())){
it.remove();
m_log.trace("file"+ test+ "is deleted from list");
m_log.trace(" NEW ORIGINAL FILE NOTIFICATION LIST ::" + EAServer.fileNotification ) ;
}
}
return null;
}
catch(Exception e){
m_log.trace(" CCCCCC IN exception" + e.getMessage());
return null;
}
}
}
if(!ne.getisInFtp()){
/* if((ne.getValidState() == NeInfo.NE_IS_STOPPED) || (ne.getValidState() == NeInfo.NE_IS_STOPPING)){
return null;
}*/
m_log.trace("FTP Not Set[ORIGINAL] " +notification);
ne.setisInFtp();
/* //Remove
try{
m_log.trace("Thread is going to sleep");
Thread.sleep(120000);
}
catch(Exception e){
//Do nothing
}
//Remve end */
m_log.trace("FETCH FILE USING NOTIFICATION[ORIGINAL] " +notification);
m_log.trace("====Returning from ORIGINAL LIST===== " + Thread.currentThread().getName());
return notification;
}
else{
m_log.trace("FTP Set.ADDING NOTIFICATION BACK TO RETRY QUEUE:::: ::: "+notification);
// EAServer.fileNotification.add(notification);
FtpWorker.isRetryList = true;
retrylist.add(notification);
m_log.trace("===+Returning NULL from ORIGINAL LIST===== " + Thread.currentThread().getName());
return null;
}
}
return null;
}
private void idle() {
while (m_running) {
// m_log.trace("ftp wroker" + Thread.currentThread().getName() + " is active");
final String task = getTask();
if (task != null ) {
// if a task is found increment working threads and run work as long
// there exists tasks.
work(task);
}
/* else{
m_log.trace("task is null which means no file notifications received yet");
}*/
try {
//m_log.trace("No TASK.SLEEPING" + Thread.currentThread().getName());
sleep(m_workerSleep);
}
catch (InterruptedException e) {
interruptEvent(e);
}
}
}
private void work(final String t) {
String task = t;
do {
m_eaServer.execute(task);
m_log.trace("TASK EXECUTED :::: " + task + " by Thread " + Thread.currentThread().getName());
yield();
task = getTask();
}
while ((task != null) && m_running);
}
public void shutDown() {
m_running = false;
}
/**
* Generates and logs an event. Should be called when the the worker
* shutdowns.
*/
protected void shutDownEvent() {
m_log.event("worker " + super.getName() + " has stopped.",
LogEventType.KERNEL_WORKER_EVENT);
}
/**
* Generates and logs an event from the given Exception. Should be called when
* the worker has been interupted.
*
* @param e the exception.
*/
protected void interruptEvent(final Exception e) {
m_log.event("worker " + super.getName() + " has interrupted, cause by "
+ e.getMessage() + ".", LogEventType.KERNEL_WORKER_EVENT);
}
}
最佳答案
如果线程在没有记录关闭事件的情况下退出,那么我会假设有什么东西抛出了运行时异常。对于初学者,我会尝试以下操作来查看抛出的内容:
public void run() {
try {
idle();
shutDownEvent();
} catch (Throwable e) {
m_log.critical(e.getMessage();
}
}
关于Java线程被杀死,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22346214/
我正在编写一个具有以下签名的 Java 方法。 void Logger(Method method, Object[] args); 如果一个方法(例如 ABC() )调用此方法 Logger,它应该
我是 Java 新手。 我的问题是我的 Java 程序找不到我试图用作的图像文件一个 JButton。 (目前这段代码什么也没做,因为我只是得到了想要的外观第一的)。这是我的主课 代码: packag
好的,今天我在接受采访,我已经编写 Java 代码多年了。采访中说“Java 垃圾收集是一个棘手的问题,我有几个 friend 一直在努力弄清楚。你在这方面做得怎么样?”。她是想骗我吗?还是我的一生都
我的 friend 给了我一个谜语让我解开。它是这样的: There are 100 people. Each one of them, in his turn, does the following
如果我将使用 Java 5 代码的应用程序编译成字节码,生成的 .class 文件是否能够在 Java 1.4 下运行? 如果后者可以工作并且我正在尝试在我的 Java 1.4 应用程序中使用 Jav
有关于why Java doesn't support unsigned types的问题以及一些关于处理无符号类型的问题。我做了一些搜索,似乎 Scala 也不支持无符号数据类型。限制是Java和S
我只是想知道在一个 java 版本中生成的字节码是否可以在其他 java 版本上运行 最佳答案 通常,字节码无需修改即可在 较新 版本的 Java 上运行。它不会在旧版本上运行,除非您使用特殊参数 (
我有一个关于在命令提示符下执行 java 程序的基本问题。 在某些机器上我们需要指定 -cp 。 (类路径)同时执行java程序 (test为java文件名与.class文件存在于同一目录下) jav
我已经阅读 StackOverflow 有一段时间了,现在我才鼓起勇气提出问题。我今年 20 岁,目前在我的家乡(罗马尼亚克卢日-纳波卡)就读 IT 大学。足以介绍:D。 基本上,我有一家提供簿记应用
我有 public JSONObject parseXML(String xml) { JSONObject jsonObject = XML.toJSONObject(xml); r
我已经在 Java 中实现了带有动态类型的简单解释语言。不幸的是我遇到了以下问题。测试时如下代码: def main() { def ks = Map[[1, 2]].keySet()
一直提示输入 1 到 10 的数字 - 结果应将 st、rd、th 和 nd 添加到数字中。编写一个程序,提示用户输入 1 到 10 之间的任意整数,然后以序数形式显示该整数并附加后缀。 public
我有这个 DownloadFile.java 并按预期下载该文件: import java.io.*; import java.net.URL; public class DownloadFile {
我想在 GUI 上添加延迟。我放置了 2 个 for 循环,然后重新绘制了一个标签,但这 2 个 for 循环一个接一个地执行,并且标签被重新绘制到最后一个。 我能做什么? for(int i=0;
我正在对对象 Student 的列表项进行一些测试,但是我更喜欢在 java 类对象中创建硬编码列表,然后从那里提取数据,而不是连接到数据库并在结果集中选择记录。然而,自从我这样做以来已经很长时间了,
我知道对象创建分为三个部分: 声明 实例化 初始化 classA{} classB extends classA{} classA obj = new classB(1,1); 实例化 它必须使用
我有兴趣使用 GPRS 构建车辆跟踪系统。但是,我有一些问题要问以前做过此操作的人: GPRS 是最好的技术吗?人们意识到任何问题吗? 我计划使用 Java/Java EE - 有更好的技术吗? 如果
我可以通过递归方法反转数组,例如:数组={1,2,3,4,5} 数组结果={5,4,3,2,1}但我的结果是相同的数组,我不知道为什么,请帮助我。 public class Recursion { p
有这样的标准方式吗? 包括 Java源代码-测试代码- Ant 或 Maven联合单元持续集成(可能是巡航控制)ClearCase 版本控制工具部署到应用服务器 最后我希望有一个自动构建和集成环境。
我什至不知道这是否可能,我非常怀疑它是否可能,但如果可以,您能告诉我怎么做吗?我只是想知道如何从打印机打印一些文本。 有什么想法吗? 最佳答案 这里有更简单的事情。 import javax.swin
我是一名优秀的程序员,十分优秀!