السلام عليكم
هناك بعض الفنكشن التي لم افهم ما مبدأ عملها
هي مثود الـ run
public class ArrayWriter implements Runnable{
public final SimpleArray SharedSimpleArray;
private final int StartValue;
public ArrayWriter(int Value, SimpleArray array){
StartValue = Value;
SharedSimpleArray = array;
}// end constructor//With constructor we need to do ovarraid for run methodv
public void run(){
for(int i = StartValue; i <StartValue+3; i++ )
{
SharedSimpleArray.add(i);// add an element to the shared array
}//end for
}//end run
}// end class ArrayWriterهذه كلاس اخرى قد بني منها الاوبجكت
public class SimpleArray { // not thread Safe
private final int array[]; // the shared int array
private int WritIndex = 0;
private final Random generator = new Random();
public SimpleArray (int size){
array = new int [size];
}// end constructor
public void add (int value)
{
int position = WritIndex;
try{// put thread to sleep
Thread.sleep(generator.nextInt(5000));
}// end try
catch (InterruptedException ex){
System.out.println("Interrupted");
}//end catch
array [position] = value;
System.out.printf
("%s wrote %2d to element %d \n ", Thread.currentThread().getName(),value,position);
// name of pool thread , name of thread in the pool
// %2d locatin of thread (1,2,3 11,12, 13)
++ WritIndex; //(increas position)
System.out.printf("Next writeindex : %d\n",WritIndex);
}// end add
public String toString(){
String arrayString = "\n contents of simple array:\n";
for (int i = 0 ; i < array.length ; i++)
arrayString += array+ " " ;
return arrayString;
}// end to string
}// end classوهذه المين كلاس
public class SharedArrayTest {
public static void main (String []arg){
//construct the shared object
SimpleArray SharedSimpleArray = new SimpleArray(6);
ArrayWriter Writer1 = new ArrayWriter(1, SharedSimpleArray);
ArrayWriter Writer2 = new ArrayWriter(11,SharedSimpleArray);
ExecutorService executer = Executors.newCachedThreadPool();
executer.execute(Writer1);
executer.execute(Writer2);
executer.shutdown();
try{// wait l minute for booth writes to finish executing
boolean tasksEnded = executer.awaitTermination(1, TimeUnit.MINUTES);
// blocks until all tasks have completed execution after shutdown or time out occurs
// or the current thread is interrupted
if (tasksEnded)
System.out.println(SharedSimpleArray);
else
System.out.println("Time out for tasks to finish");
}//end try
catch(InterruptedException e){
System.out.println("Interruption");
}// end catch
}//end main
}// end class
