我如何在线程组中替换this.stop()的弃用方法



我正在从事Java版本升级项目,并且我正在工作,需要替换不推荐使用的方法。

this.stop();

使用的代码此方法在::

threadedtestgroup.java ::

    package utmj.threaded;
import junit.framework.*;
public class ThreadedTestGroup extends ThreadGroup {
    private Test test;
    private TestResult testResult;
    public ThreadedTestGroup(Test test) {
        super("ThreadedTestGroup");
        this.test = test;
    }

    public void interruptThenStop() {
        this.interrupt();
        if (this.activeCount() > 0) {
        this.stop(); // For those threads which won't interrupt
        }
    }

    public void setTestResult(TestResult result) {
        testResult = result;
    }

    public void uncaughtException(Thread t, Throwable e) {
        if (e instanceof ThreadDeath) {
            return;
        }
        if (e instanceof AssertionFailedError) {
            testResult.addFailure(test, (AssertionFailedError) e);
        } else {
            testResult.addError(test, e);
        }
        this.interruptThenStop();
    }
}

cobcyrrenttestcase.java

    package utmj.threaded;
import java.util.*;
import junit.framework.*;
/
public class ConcurrentTestCase extends TestCase {
    private TestResult currentResult;
    private ThreadedTestGroup threadGroup;
    private Hashtable threads = new Hashtable();
    private boolean deadlockDetected = false;
    private Vector checkpoints = new Vector();
    class ConcurrentTestThread extends Thread {
        private volatile boolean hasStarted = false;
        private volatile boolean hasFinished = false;
        ConcurrentTestThread(
            ThreadGroup group,
            Runnable runnable,
            String name) {
            super(group, runnable, name);
        }
        public void run() {
            hasStarted = true;
            super.run();
            finishThread(this);
        }
    }
    public ConcurrentTestCase(String name) {
        super(name);
    }
    public ConcurrentTestCase() {
        super();
    }
    protected void addThread(String name, final Runnable runnable) {
        if (threads.get(name) != null) {
            fail("Thread with name '" + name + "' already exists");
        }
        ConcurrentTestThread newThread =
            new ConcurrentTestThread(threadGroup, runnable, name);
        threads.put(name, newThread);
    }
    public synchronized void checkpoint(String checkpointName) {
        checkpoints.addElement(checkpointName);
        this.notifyAll();
    }
    public boolean checkpointReached(String checkpointName) {
        return checkpoints.contains(checkpointName);
    }
    public boolean deadlockDetected() {
        return deadlockDetected;
    }
    private synchronized void finishThread(ConcurrentTestThread thread) {
        thread.hasFinished = true;
        this.notifyAll();
    }
    private ConcurrentTestThread getThread(String threadName) {
        return (ConcurrentTestThread) threads.get(threadName);
    }
    /**
     * Returns true if the thread finished normally, i.e. was not inerrupted or stopped
     */
    public boolean hasThreadFinished(String threadName) {
        ConcurrentTestThread thread = this.getThread(threadName);
        if (thread == null) {
            fail("Unknown Thread: " + threadName);
        }
        return thread.hasFinished;
    }
    public boolean hasThreadStarted(String threadName) {
        ConcurrentTestThread thread = this.getThread(threadName);
        if (thread == null) {
            fail("Unknown Thread: " + threadName);
        }
        return thread.hasStarted;
    }
    private void interruptAllAliveThreads() {
        threadGroup.interruptThenStop();
    }
    /**
     * Wait till all threads have finished. Wait maximally millisecondsToWait.
     * Should only be called after startThreads().
     */
    protected void joinAllThreads(long millisecondsToWait) {
        Enumeration enum1 = threads.elements();
        long remainingMilliseconds = millisecondsToWait;
        while (enum1.hasMoreElements()) {
            long before = System.currentTimeMillis();
            ConcurrentTestThread each =
                (ConcurrentTestThread) enum1.nextElement();
            try {
                each.join(remainingMilliseconds);
            } catch (InterruptedException ignored) {
            }
            long spent = System.currentTimeMillis() - before;
            if (millisecondsToWait != 0) {
                remainingMilliseconds = remainingMilliseconds - spent;
                if (remainingMilliseconds <= 0) {
                    deadlockDetected = true;
                    break;
                }
            }
        }
    }
    public void joinThread(String threadName) throws InterruptedException {
        this.joinThread(threadName, 0);
    }
    public void joinThread(String threadName, long millisecondsToTimeout)
        throws InterruptedException {
        ConcurrentTestThread thread = this.getThread(threadName);
        if (thread == null) {
            fail("Unknown Thread: " + threadName);
        }
        thread.join(millisecondsToTimeout);
    }
    /**
     * Stores the current result to be accessible during the test
     */
    public void run(TestResult result) {
        currentResult = result;
        super.run(result);
    }
    protected void setUp() throws Exception {
        threadGroup = new ThreadedTestGroup(this);
    }
    /**
     * Sleep and ignore interruption
     */
    public void sleep(long milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException ignored) {
        }
    }
    /**
     * Run all threads and wait for them to finish without timeout
     */
    protected void startAndJoinAllThreads() {
        this.startAndJoinThreads(0);
    }

    protected void startThreads() {
        threadGroup.setTestResult(currentResult);
        Enumeration enum1 = threads.elements();
        while (enum1.hasMoreElements()) {
            ConcurrentTestThread each =
                (ConcurrentTestThread) enum1.nextElement();
            each.start();
            each.hasStarted = true;
        }
        Thread.yield();
    }

    protected void tearDown() throws Exception {
            this.interruptAllAliveThreads();
            threads = new Hashtable();
            checkpoints = new Vector();
            deadlockDetected = false;
            threadGroup = null;
            currentResult = null;
        }
    public synchronized void waitForCheckpoint(String checkpointName) {
        while (!this.checkpointReached(checkpointName)) {
            try {
                this.wait();
            } catch (InterruptedException ignored) {
            }
        }
    }

    public synchronized void waitUntilFinished(String threadName) {
        while (!this.hasThreadFinished(threadName)) {
            try {
                this.wait();
            } catch (InterruptedException ignored) {
            }
        }
    }
}

我试图对此进行搜索,但没有合适的解决方案,因此是否有人可以帮助我替换不推翻的this.stop()方法。

IDE消息:The method stop() from the type ThreadGroup is deprecated

没有一个方法可以替换线程组中的stop(),而是设计方法

从Oracle文档中说

停止的许多用途应被简单地修改的代码代替 一些变量表明目标线应停止运行。 目标线程应定期检查此变量,然后返回 如果变量指示 那是停止运行

查看样品我应该使用什么而不是线程。

private volatile Thread blinker;
public void stop() {
    blinker = null;
}
public void run() {
    Thread thisThread = Thread.currentThread();
    while (blinker == thisThread) {
        try {
            Thread.sleep(interval);
        } catch (InterruptedException e){
        }
        repaint();
    }
}

在整个线程中,您需要检查线程安全变量(在其上方的示例中)...当调用停止时,它将线程设置为null以从while循环中断并从运行中返回。。从而"停止"线程

好吧,我对为什么要弃用over()的文档有点红色,这是最相关的部分:

此方法本质上是不安全的。用线程停止线程。停机使其解锁已锁定的所有显示器(由于未检查的线Dexceptions的自然结果在堆栈中传播)。如果先前由这些监视器保护的任何对象处于不一致的状态,则受损的对象被其他线程可见,可能导致任意行为。停止的许多用途应该用代码代替,该代码简单地显示了一些变量,以表明目标线程应停止运行。目标线程应定期检查此变量,并以有序的方式从其运行方法中返回,如果该变量表明其停止运行。如果目标线程长时间等待(例如,在条件变量上),则应使用中断方法中断等待。

有了这些细节,我认为不再有一种简单的方法来停止所有线程,就像stop()一样。您可能需要修改线程,以便您有一种停止它们的方法(如果有可能的话)。

相关内容

  • 没有找到相关文章

最新更新