Java Multithreading (Schlösser und Synchronisation)Java

Java-Forum
Anonymous
 Java Multithreading (Schlösser und Synchronisation)

Post by Anonymous »

Ich versuche, einen synchronisierten Block mit Schlössern aus einigen alten Tutorials anzuwenden. Die App dauert 2 Sekunden im Tutorial, aber meine hat 4 Sekunden aufgrund des Threads. Ich weiß nicht, warum 1Ms einen Unterschied von 2 Sekunden machen. Ohne zu schlafen, dauert mein Code nur 2 ms, ist es die JVM -Version? Was fehlt mir?

Code: Select all

worker worker = new worker();
Thread t1 = new Thread(worker::process);
Thread t2 = new Thread(worker::process);

long startThreads = System.currentTimeMillis();

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("Time taken: " + (end - startThreads) + " ms");
< /code>
class worker {
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
final Object lock1 = new Object();
final Object lock2 = new Object();
Random random = new Random();
public void stage1() {
synchronized (lock1) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

list1.add(random.nextInt(100));
}
}

public void stage2() {
synchronized (lock2) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
list2.add(random.nextInt(100));

}
}

public void process() {
for (int i = 0; i < 1000; i++) {
stage1();
stage2();
}
}

public void processsequntially() {
for (int i = 0; i < 1000; i++) {
stage1();
stage2();
}
}

}

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post