【问题标题】:Java Thread - synchronization threadJava Thread - 同步线程
【发布时间】:2016-05-04 18:58:44
【问题描述】:

我有这样的事情:

 enter code here

public class Main {

public static void main(String[] args) throws InterruptedException {
    StringTask task = new StringTask("A", 100000);
    System.out.println("Task " + task.getState());
    task.start();
    if (args.length > 0 && args[0].equals("abort")) {

        Thread t = new Thread(() -> {
            Thread.currentThread();
            try {
                Thread.sleep(1000);
                task.abort();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        });
        t.start();
    }
    while (!task.isDone()) {
        Thread.sleep(500);
        switch (task.getState()) {
        case "RUNNING":
            System.out.print("R.");
            break;
        case "ABORTED":
            System.out.println(" ... aborted.");
            break;
        case "READY":
            System.out.println(" ... ready.");
            break;
        default:
            System.out.println("uknown state");
        }

    }
    System.out.println("Task " + task.getState());
    System.out.println(task.getResult().length());
}

}

class StringTask implements Runnable {
private String word;

private int nr;
private boolean stopThread = false;
private String result = "";
private String state = "";
private boolean done = false;
private boolean end = false;
public Thread thread;

public StringTask(String s, int n) {
    this.word = s;
    this.nr = n;
    this.state = "CREATED";
}

public void STOP() {
    this.stopThread = true;
}

public void run() {
    this.state = "RUNNING";
        try {
            for (int i = 0; i < nr; i++) {
                result += word;
            }
            this.state = "READY";
            this.done = true;
        } catch (Exception e) {
            this.state = "ABORTED";
            this.done = false;

        }

    }

public synchronized void start() {
    thread = new Thread(this);
    thread.start();
}

public synchronized void abort() throws Exception {
    thread.interrupt();
    this.end = true;
    this.done = true;
    this.state = "ABORTED";

}

public String getResult() {
    return this.result;
}

public String getState() {

    return this.state;
}

public boolean isDone() {
    return this.done;
}
 }

所以,如果我运行不带参数的程序(我的意思是 String args[])程序可以正常工作,但如果我设置 agument = abort

我的程序应该打印如下内容:

任务已创建 R. ...中止。 任务中止 31700

有时他打印得很好,但有时他会打印这样的东西:

任务已创建 R.R.任务中止 58891

还有这样的:

任务已创建 R.R. ...准备好了。 任务就绪 70000

但我不知道为什么,所以我的问题是:

如何正确同步线程,以便他们可以做他们应该做的?

【问题讨论】:

  • 在问题中发布相关代码。不在pastebin。
  • 那么,他们应该怎么做呢?你读过interrupt()的文档吗?

标签: java multithreading interruption


【解决方案1】:

没有任何有意义的共享状态(设置了一些标志,其中读取它们的代码未同步,因此它们可能无法获取更新的值,但似乎没有使用这些字段)所以同步在这里不是问题。

你的任务的 run 方法不处理中断(例如,它不检查Thread.currentThread().isInterrupted()),所以调用中断没有效果。中断需要被中断的任务通过检查是否被中断并采取措施结束自身来进行合作。您可以更改循环以测试中断,例如:

       for (int i = 0; i < nr; i++) {
            result += word;
            if (Thread.currentThread().isInterrupted()) {
                break;
            }
        }

你有一个线程将字符连接到一个字符串上,它获得多少 CPU 时间取决于操作系统,它必须决定在这里给每个线程多少时间,以及给 JVM 和其他正在执行的进程多少时间在你的电脑。有时您的任务可能在线程试图中断它之前完成,有时它可能不会,这会影响打印出的状态。当你重复运行它时,你应该期望得到不同的结果。

【讨论】:

    猜你喜欢
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多