【问题标题】:implementing synchronization to get the proper threads output properly实现同步以正确获取正确的线程输出
【发布时间】:2014-10-12 06:27:59
【问题描述】:

目前,当我运行程序时,线程是随机运行的。例如当前的输出是:

Global.sharedBuffer[0] = 2
Global.sharedBuffer[1] = 1
Global.sharedBuffer[2] = 1
Global.sharedBuffer[3] = 1
Global.sharedBuffer[4] = 1
Global.sharedBuffer[5] = 1
Global.sharedBuffer[6] = 1
Global.sharedBuffer[7] = 1
Global.sharedBuffer[8] = 1
Global.sharedBuffer[9] = 1
Global.sharedBuffer[10] = 2
Global.sharedBuffer[11] = 4
Global.sharedBuffer[12] = 3

我想要的是从 sharedBuffer 0 到 9 全为 1,然后从 10 - 19 全为 2 等等。我添加了一个同步块,认为它会这样做,但是,它只是在每次线程时停止上下文切换叫。您如何着手实现这一点?

代码:

import java.io.*;
import java.lang.*;
import java.util.*;

class MyThreadExample2 {
public static void main(String[] args) {
   HelloThread ht1 = new HelloThread(1);
   HelloThread ht2 = new HelloThread(2);
   HelloThread ht3 = new HelloThread(3);
   HelloThread ht4 = new HelloThread(4);
   ht1.start();
   ht2.start();
   ht3.start();
   ht4.start();
   }
}

class Global {
    public static int[] sharedBuffer = new int[1000];
    public static int in = 0;
}


class HelloThread extends Thread {
    int threadID;

    HelloThread(int threadID) {
System.out.println("threadID:  " + threadID);
    this.threadID = threadID;
    }

    public synchronized void run() {
       for (int i = 0; i < 100; i++) {



if((Global.in >= 0 || Global.in <= 99) && (this.threadID == 1))
       Global.sharedBuffer[Global.in] = this.threadID;

else if((Global.in >= 100 || Global.in <= 199) && (this.threadID == 2))
       Global.sharedBuffer[Global.in] = this.threadID;

else if((Global.in >= 200 || Global.in <= 299) && (this.threadID == 3))
       Global.sharedBuffer[Global.in] = this.threadID;

else if((Global.in >= 300 || Global.in <= 399) && (this.threadID == 4))
       Global.sharedBuffer[Global.in] = this.threadID;



System.out.println("Thread " + this.threadID + " has written " 
        + this.threadID + " to Global.sharedBuffer[" + Global.in + "]\n");


       Global.in++;
       }

    if (this.threadID == 4) 
    {
        try {this.sleep(2000L);
    } 
        catch (Throwable e) {e.printStackTrace();
    }

System.out.println("The final buffer is **************\n");
       for (int i = 0; i < 30; i++) {
    System.out.println("Global.sharedBuffer[" + i + "] = " + 
                            Global.sharedBuffer[i]);
       } // for
    } // if
   } // run




} // end Thread

【问题讨论】:

  • 不要使用全局 in 变量 - 所有线程都在同时更新它,这是一种大数据竞争条件。只需使用本地索引计数器,该计数器从应开始的位置开始并在应结束的位置结束。
  • 如果你想要顺序执行,为什么要使用线程?

标签: java multithreading concurrency operating-system synchronization


【解决方案1】:

仅当您可以制定可以独立于其他人执行的任务时,多线程才有效。您必须避免共享变量,如果无法避免,则必须对访问进行适当的保护,这通常意味着限制线程执行的并发性。

对于您的任务,制定独立任务很简单,因为每个线程都应写入数组的不同区域:

public class ThreadingExample {
    public static void main(String[] args) {
        final int numThread=4, chunkSize=10;
        int[] array=new int[numThread*chunkSize];
        Thread[] thread=new Thread[numThread];

        // create threads and define their jobs
        for(int t=0, p=0; t<numThread; t++, p+=chunkSize) {
            thread[t]=new Thread(new FillInJob(array, t, p, chunkSize));
        }

        // start the threads
        for(Thread t: thread) t.start();
        // now all running concurrently

        // wait for completion
        try {
            for(Thread t: thread) t.join();
        } catch(InterruptedException ex) {
            throw new AssertionError(ex);
        }

        // use result
        System.out.println(java.util.Arrays.toString(array));
    }
}
class FillInJob implements Runnable {
    private final int[] targetArray;
    private final int myID, startIndex, endIndex;

    FillInJob(int[] target, int id, int start, int size) {
      targetArray=target;
      myID=id;
      startIndex=start;
      endIndex=start+size;
    }

    public void run() {
        for(int ix=startIndex; ix<endIndex; ix++)
            targetArray[ix]=myID;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2012-02-05
    • 1970-01-01
    相关资源
    最近更新 更多