0

嗨,我在我的程序中运行多个线程,每个线程包含 6 个元素的数组。我在线程的运行方法中添加了同步,但只有第一个线程是同步的,以从 1 到 6 的顺序显示数组。

/* My run method for the thread */
public synchronized void run(){
    int from = St7.stt[acnt].getCf();
    int to = St7.stt[acnt].getCt();
    int inc = St7.stt[acnt].getCi();
    threadsRunning++; // We now have more threads 
    this.threadId = threadsRunning;
    active = true;
    try{
        int loop = from;
        while (active && loop <= to){

            System.out.println(text + " Counter: " + St7.stt[acnt].getCounter() + ".");
            System.out.println();
            Thread.sleep(sleep);
            loop=loop+inc;
        }
4

2 回答 2

1

据我了解,您希望线程的结果与它们被调度的顺序相同,如果这是正确的,Callable接口可能会帮助您:它允许您在多个线程中执行,但您也可以获得每个线程的返回按照您执行它们的顺序执行线程(检查here)。

于 2013-03-23T23:20:48.037 回答
0

我不确定我是否理解这个问题,并且变量命名不佳也无济于事,但似乎您正在创建 StudentThread 类的 N 个实例,它们的run()方法都已同步。

这不会阻止多个线程同时调用 run 方法,因为它们都在单独的对象上同步。为了实现互斥,所有线程必须在一个唯一对象上同步,该对象应该封装必须防止并发访问的共享状态。

于 2013-03-23T23:09:35.690 回答