Java MulthiThreading Equal Cards divide with 4 threads

jcvallenato

New Member
I am trying to learn multi-threading by implementing code snippets. The problem is to distribute cards(52) among four lists using 4 threads(13 each), please suggest better solution or correction in below code.As this is for practice on multi-threading, I have not made much stress on naming conventions and generics (apologies for this)\[code\]import java.util.LinkedList;import java.util.List;public class CardsDivideIntoFour { static final int Max = 52; static int val = 0; static Object ox = new Object(); static List list1 = new LinkedList(); static List list2 = new LinkedList(); static List list3 = new LinkedList(); static List list4 = new LinkedList(); public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { public void run() { while (true) { if (val >= Max) { break; } synchronized (ox) { list1.add(++val); System.out.println("a> " + val); ox.notifyAll(); try { if (val >= Max) { // System.out.println("t1 run finished"); // Thread.currentThread().interrupt(); break; } Thread.sleep(1000); ox.wait(); } catch (InterruptedException e) { } } } // Unreachable code // System.out.println("t1 run finished"); } }); Thread t2 = new Thread(new Runnable() { public void run() { while (true) { if (val >= Max) { break; } synchronized (ox) { list2.add(++val); System.out.println("b> " + val); ox.notifyAll(); try { if (val >= Max) { break; } Thread.sleep(1000); ox.wait(); } catch (InterruptedException e) { } } } } }); Thread t3 = new Thread(new Runnable() { public void run() { while (true) { if (val >= Max) { break; } synchronized (ox) { list3.add(++val); System.out.println("c> " + val); ox.notifyAll(); try { if (val >= Max) { break; } Thread.sleep(1000); ox.wait(); } catch (InterruptedException e) { } } } } }); Thread t4 = new Thread(new Runnable() { public void run() { while (true) { if (val >= Max) { break; } synchronized (ox) { list4.add(++val); System.out.println("d> " + val); ox.notifyAll(); try { if (val >= Max) { break; } Thread.sleep(1000); ox.wait(); } catch (InterruptedException e) { } } } } }); t1.start(); t2.start(); t3.start(); t4.start(); try { t1.join(); t2.join(); t3.join(); t4.join(); } catch (Exception e) { } System.out.print("List1 has > "); for (Object o : list1) { System.out.print((Integer) o + ","); } System.out.println(""); System.out.print("List2 has > "); for (Object o : list2) { System.out.print((Integer) o + ","); } System.out.println(""); System.out.print("List3 has > "); for (Object o : list3) { System.out.print((Integer) o + ","); } System.out.println(""); System.out.print("List4 has > "); for (Object o : list4) { System.out.print((Integer) o + ","); } }}\[/code\]
 
Back
Top