简体   繁体   English

Java Thread - 同步线程

[英]Java Thread - synchronization thread

I have something like this:我有这样的事情:

 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;
}
 }

So, if I run program withou arguments (I mean String args[]) program works okay, but if I set agument = abort所以,如果我运行没有参数的程序(我的意思是 String args[])程序工作正常,但如果我设置 agument = abort

My program should print something like this:我的程序应该打印如下内容:

Task CREATED R. ... aborted.任务 CREATED R. ... 中止。 Task ABORTED 31700任务中止 31700

sometimes he print good but sometimes he print something like this:有时他打印得很好,但有时他打印的东西是这样的:

Task CREATED RRTask ABORTED 58891任务创建 RRTask 中止 58891

and something like this:和这样的事情:

Task CREATED RR ... ready.任务已创建 RR ... 准备就绪。 Task READY 70000任务就绪 70000

but I don't know why, so my question is:但我不知道为什么,所以我的问题是:

How to correctly synchronise threads so they can do what they should?如何正确同步线程以便他们可以做他们应该做的事?

There isn't any meaningful shared state (there are some flags that get set, where the code that reads them is not synchronizing so they may not be getting the updated value, but those fields don't seem to be used) so synchronization is not an issue here.没有任何有意义的共享状态(有一些标志被设置,读取它们的代码没有同步,所以它们可能没有得到更新的值,但这些字段似乎没有被使用)所以同步是这里不是问题。

Your task's run method doesn't handle interruption (for instance, it doesn't check Thread.currentThread().isInterrupted() ) so calling interrupt has no effect.您的任务的 run 方法不处理中断(例如,它不检查Thread.currentThread().isInterrupted() ),因此调用中断无效。 Interruption requires the task being interrupted to cooperate by checking whether it's been interrupted and taking measures to end itself.中断要求被中断的任务通过检查它是否被中断并采取措施结束自己来进行协作。 You could change the loop to test for interruption, with something like:您可以更改循环以测试中断,例如:

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

You have one thread concatenating chars onto a string, and how much CPU time it gets depends on the OS, it has to decide how much time to give each thread here and also how much time to give the JVM versus other processes executing on your computer.你有一个线程将字符连接到一个字符串上,它获得多少 CPU 时间取决于操作系统,它必须决定在这里给每个线程多少时间,以及给 JVM 多少时间与在您的计算机上执行的其他进程. Sometimes your task may finish before the thread trying to interrupt it, other times it may not, which affects what state gets printed out.有时您的任务可能会在线程试图中断它之前完成,有时可能不会,这会影响打印出的状态。 You should expect to get different results when you run it repeatedly.当您重复运行它时,您应该期望得到不同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM