could somebody explain me this task ? how does it work (code).
the code :
import java.util.ArrayList;
import java.util.List;
/*
Razem szybciej? Zobaczymy :)
*/
public class Solution {
public static class SortThread extends Thread{
public void run(){
sort(testArray);
}
}
public static int threadCount = 10;
public static int[] testArray = new int[1000];
static {
for (int i = 0; i < Solution.testArray.length; i++) {
testArray[i] = i;
}
}
public static void main(String[] args) throws InterruptedException {
StringBuffer expectedResult = new StringBuffer();
for (int i = 1000 - 1; i >= 0; i--) {
expectedResult.append(i).append(" ");
}
initThreads();
StringBuffer result = new StringBuffer();
for (int i = 0; i < testArray.length; i++) {
result.append(testArray[i]).append(" ");
}
System.out.println(result);
System.out.println((result.toString()).equals(expectedResult.toString()));
}
public static void initThreads() throws InterruptedException {
List<Thread> threads = new ArrayList<Thread>(threadCount);
for (int i = 0; i < threadCount; i++) threads.add(new SortThread());
for (Thread thread : threads) thread.start();
for (Thread thread : threads) thread.join();
}
public static void sort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] < array[j]) {
int k = array[i];
array[i] = array[j];
array[j] = k;
}
}
}
}
}
I have made it but I do not understand it at all
Dyskutowane
Komentarze (2)
- Popularne
- Najnowsze
- Najstarsze
Musisz się zalogować, aby dodać komentarz
Mariusz
23 grudnia 2020, 15:59
I don't quite understand that task but my solution passed the validation:
public static class SortThread extends Thread {
@Override
public void run() {
synchronized(this) {
sort(testArray);
}
}
}
But on my machine it returns 'false' or 'true' regardless of 'synchronized' keyword which isn't correct as the sorting haven't been done right. Nevertheless it passes testing somehow.
0
Nouser
23 grudnia 2020, 17:38
If you want to get true as result then you could try to synchronize on testArray or the SortThread class.
this synchronizes the object but here the non local data that is used by all threads is static. Therefore all the objects can use it, it's not object only data. If it was a field, this would work.
0