Created
March 25, 2024 06:10
-
-
Save honux77/2f5943a691d35bfcc9df8f7124365aa7 to your computer and use it in GitHub Desktop.
Bad Thread Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.example; | |
public class Main { | |
public static long result = 0; | |
public static void main(String[] args) { | |
final int NUM_THREADS = 10; | |
final long START_NUM = 0; | |
//final long END_NUM = 300000000; | |
final long END_NUM = 10000000; | |
final long STEP = (END_NUM - START_NUM) / NUM_THREADS; | |
Thread[] threads = new Thread[NUM_THREADS]; | |
for (int i = 0; i < threads.length; i++) { | |
long start = i * STEP + 1; | |
long end = (i + 1) * STEP; | |
threads[i] = new Thread(new MyRunnable(start, end)); | |
threads[i].start(); | |
} | |
for (int i = 0; i < threads.length; i++) { | |
try { | |
threads[i].join(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
System.out.println("Result: " + Main.result); | |
System.out.println("Program ended..."); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.example; | |
public class MyRunnable implements Runnable { | |
public long s; | |
public long e; | |
public MyRunnable(Long s, Long e) { | |
this.s = s; | |
this.e = e; | |
} | |
public synchronized void someMethod() { | |
System.out.println(s + " " + e); | |
for (long i = s; i <= e; i++) { | |
Main.result += i; | |
} | |
System.out.println("Thread " + Thread.currentThread().getName() + " finished."); } | |
@Override | |
public void run() { | |
someMethod(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment