| 1 | |
|---|
| 2 | package tmcsim.client.cadclientgui.data; |
|---|
| 3 | |
|---|
| 4 | import java.util.ArrayList; |
|---|
| 5 | import java.util.Vector; |
|---|
| 6 | import javax.swing.table.DefaultTableModel; |
|---|
| 7 | |
|---|
| 8 | |
|---|
| 9 | /** |
|---|
| 10 | * A simple demo of how to use threads and "synchronized" |
|---|
| 11 | * |
|---|
| 12 | * @author jdalbey |
|---|
| 13 | */ |
|---|
| 14 | public class ThreadDemo |
|---|
| 15 | { |
|---|
| 16 | static ArrayList<Integer> numbers; |
|---|
| 17 | |
|---|
| 18 | public static void main(String args[]) |
|---|
| 19 | { |
|---|
| 20 | System.out.println("Testing threads"); |
|---|
| 21 | PrintFunctor pf=new PrintFunctor(); |
|---|
| 22 | Threadserve ts1=new Threadserve(pf,12,"A"); |
|---|
| 23 | Threadserve ts2=new Threadserve(pf,8,"B"); |
|---|
| 24 | Threadserve ts3=new Threadserve(pf,6,"C"); |
|---|
| 25 | } |
|---|
| 26 | |
|---|
| 27 | static class Threadserve implements Runnable |
|---|
| 28 | { |
|---|
| 29 | int max; |
|---|
| 30 | String id; |
|---|
| 31 | PrintFunctor pf; |
|---|
| 32 | Thread th; |
|---|
| 33 | Threadserve(PrintFunctor printer,int x, String id) |
|---|
| 34 | { |
|---|
| 35 | this.max = x; |
|---|
| 36 | this.id = id; |
|---|
| 37 | pf = printer; |
|---|
| 38 | th=new Thread(this); |
|---|
| 39 | th.start(); |
|---|
| 40 | } |
|---|
| 41 | public void run() |
|---|
| 42 | { |
|---|
| 43 | pf.countdown(max,id); |
|---|
| 44 | } |
|---|
| 45 | } |
|---|
| 46 | static class PrintFunctor |
|---|
| 47 | { |
|---|
| 48 | public PrintFunctor() |
|---|
| 49 | { |
|---|
| 50 | } |
|---|
| 51 | synchronized |
|---|
| 52 | void countdown(int max, String id) |
|---|
| 53 | { |
|---|
| 54 | numbers = new ArrayList<Integer>(); |
|---|
| 55 | for (int num=0; num <100; num++) |
|---|
| 56 | { |
|---|
| 57 | numbers.add(num); |
|---|
| 58 | } |
|---|
| 59 | System.out.println("Start" + id); |
|---|
| 60 | for(int idx=max; idx>0; idx--) |
|---|
| 61 | { |
|---|
| 62 | try |
|---|
| 63 | { |
|---|
| 64 | // when halfway, pause |
|---|
| 65 | if(idx==max/2) Thread.sleep(100); |
|---|
| 66 | } |
|---|
| 67 | catch(InterruptedException e) |
|---|
| 68 | { ; } |
|---|
| 69 | System.out.println(id + ": " + idx + "," + numbers.get(idx)); |
|---|
| 70 | } |
|---|
| 71 | System.out.println(); |
|---|
| 72 | numbers.clear(); |
|---|
| 73 | System.out.println("Done countdown." + id); |
|---|
| 74 | } |
|---|
| 75 | } |
|---|
| 76 | } |
|---|