Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Author: Matheus Eduardo Garbelini
- // Code: Philosophers dinner
- import java.util.Random;
- public class Deadlock {
- static CrazyThread[] Threads; // Stores the thread classes
- static Object[] Locks; // Stores the locks
- static String[] LocksFlags;
- public static void main(String[] args) {
- // Initialize n threads, where n is the number of cores on current machine
- int ncores = Runtime.getRuntime().availableProcessors();
- System.out.println("Number of available cores: " + ncores);
- Locks = new Object[ncores];
- Threads = new CrazyThread[ncores];
- LocksFlags = new String[ncores];
- // Initialize threads
- for (int i = 0; i < ncores; i++) {
- LocksFlags[i] = "_";
- Locks[i] = new Object();
- Threads[i] = new CrazyThread();
- Threads[i].ncore = i;
- Threads[i].maxcores = ncores;
- System.out.println("Core number: " + i);
- }
- // Start threads
- for (int i = 0; i < ncores; i++) {
- Threads[i].start();
- }
- }
- public static class CrazyThread extends Thread {
- public int ncore;
- public int maxcores;
- public Random random = new Random(); // Each seed is different at class allocation (nanoTime used)
- public void run() {
- while (true) {
- int start_delay = random.nextInt(10);
- int busy_delay = random.nextInt(100);
- threadSleep(start_delay);
- synchronized (Locks[ncore]) {
- LocksFlags[ncore] = String.valueOf(ncore); // Set flag for first lock
- printThreads(); // print locks status
- int next_lock = (ncore + 1) % maxcores;
- synchronized (Locks[next_lock]) {
- LocksFlags[next_lock] = String.valueOf(ncore); // Set flag for second lock
- printThreads(); // print locks status
- threadSleep(busy_delay);
- }
- LocksFlags[next_lock] = "_";
- }
- LocksFlags[ncore] = "_";
- printThreads(); // Print freed locks
- }
- }
- void threadSleep(int ms) {
- try { // Yes, java requires to use an exception even to sleep a thread, oh my god!!!
- Thread.sleep(ms);
- } catch (Exception e) {
- }
- }
- void printThreads() {
- String threadsText = "";
- for (int i = 0; i < maxcores; i++) {
- if (i == 0)
- threadsText += "["; // first lock flag
- threadsText += LocksFlags[i];
- if (i == maxcores - 1)
- threadsText += "]";
- else
- threadsText += ",";
- }
- System.out.println(threadsText);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement