我已经创建了java线程示例程序,在该示例程序中,我使用了stop()方法来使用下面的程序停止线程
public class App extends Thread
{
Thread th;
App(String threadName)
{
th = new Thread(threadName);
}
public synchronized void run() // Remove synchronized
{
for (int i = 0; i < 5; i++) {
System.out.println(th.getName()+" "+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
public static void main( String[] args )
{
App thread_1 = new App("Thread-1");
thread_1.start();
thread_1.setPriority(MAX_PRIORITY); //Comment this
thread_1.stop();
App thread_2 = new App("Thread-2");
thread_2.start();
}
}上述程序的输出如下:
Thread-1 0
Thread-1 1
Thread-1 2
Thread-1 3
Thread-1 4
Thread-2 0
Thread-2 1
Thread-2 2
Thread-2 3
Thread-2 4也就是说,thread_1没有停止。当我移除代码线程中的同步或优先级时,线程立即停止,输出将被
Thread-2 0
Thread-2 1
Thread-2 2
Thread-2 3
Thread-2 4我不明白它为什么会这样运作。
发布于 2015-01-21 20:11:50
线程类的大多数公共方法都是在线程实例本身上同步的。http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/5672a2be515a/src/share/classes/java/lang/Thread.java
您的run()方法在Thread实例上是同步的。stop()方法调用stop(Throwable),该方法在Thread实例上也是同步的,其签名是:
@Deprecated
public final synchronized void stop(Throwable obj) {同步防止主线程进入thread_1.stop(),而线程本身仍在synchronized run()方法中运行。
这是为什么总是使用私有对象进行同步是明智的例子。例如,做这个。
class Foobar {
private final Object lock = new Object();
public void do_something() {
synchronized(lock) {
...
}
}
}而不是这么做..。
class Foobar {
public synchronized void do_something() {
...
}
}第二个版本更详细(欢迎来到Java!),但它阻止了Foobar类的用户将其作为同步对象使用,从而干扰了它本身作为同步对象的使用。
发布于 2015-01-21 06:13:49
Thread.stop()被否决了。考虑使用以下方法:
public class App extends Thread
{
Thread th;
volatile boolean bStopThread;
App(String threadName)
{
th = new Thread(threadName);
bStopThread = false;
}
public void stopThread(){
bStopThread = true;
}
public synchronized void run() // Remove synchronized
{
for (int i = 0; i < 5; i++) {
if(bStopThread) return;
System.out.println(th.getName()+" "+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
public static void main( String[] args ) throws InterruptedException
{
App thread_1 = new App("Thread-1");
thread_1.start();
thread_1.setPriority(MAX_PRIORITY); //Comment this
thread_1.stopThread();
App thread_2 = new App("Thread-2");
thread_2.start();
}
}虽然我还没有测试过,但它应该可以按您的要求工作。
发布于 2015-01-21 06:14:14
应用程序中有三个线程:主线程,运行main方法的代码thread_1和thread_2。主线程在X的某个时间点启动thread_1,然后在某个时间点调用thread_1.stop(),Y,Y>X。
现在,在X点和Y点之间可能发生的情况是,CPU调度程序可以决定:“我现在让thread_1运行”。Thread_1将获得CPU,运行并打印他的文本。或者,CPU调度程序可以决定:“主线程现在正在运行.让它运行”。而thread_1将不会得到CPU直到停止被调用,并将不打印任何。
因此,在CPU调度的控制范围之外,存在不确定性。您只能假设提高线程的优先级会提示调度程序选择上述选项中的第一个。
但。停止是不可取的,所以永远不要使用它。不要试图猜测多线程的执行顺序。
https://stackoverflow.com/questions/28060428
复制相似问题