首页 > 代码库 > 多线程

多线程

题目:启动3个线程打印递增的数字,线程1打印1,2,3,4,5,然后是线程2打印6,7,8,9,10,然后是线程3打印11,12,13,14,15.接着线程1打印16,17,18,19,20.。。以此类推,直到打印到75.

 1 public class Main { 2  3     /** 4      * @param args 5      */ 6     public static void main(String[] args) { 7         Nums nums = new Nums(); 8         new Thread(new task("线程1", nums, 1)).start(); 9         new Thread(new task("线程2", nums, 2)).start();10         new Thread(new task("线程3", nums, 0)).start();11         12     }13 }14 class task implements Runnable{15 16     String taskName;17     Nums obj;18     int taskNum;19     20     public task(String name, Nums nums, int n){21         taskName = name;22         this.obj = nums;23         taskNum = n;24     }25     26     @Override27     public void run() {28         29         while(true){30             31             if (obj.getLable() == taskNum) {32                 System.out.print(taskName + "正在打印:");33                 obj.print();34                 System.out.println();35                 36                 //某个线程在打印完75后结束次线程。37                 if (obj.getLastNum() == 75) {38                     break;39                 } else {40                     obj.addFive();41                 }42                 43             } else {44                 try {45                     //其他线程在不能够打印含有75的数组,达到结束的要求时,结束此线程。46                     if (obj.getLastNum() >= 75) {47                         break;48                     }49                     Thread.sleep(100);50                 } catch (InterruptedException e) {51                     e.printStackTrace();52                 }53             }54             55         }56         57     }58     59 }60 class Nums {61     public int[] nums;62     public Nums(){63         nums = new int[5];64         for (int i = 0; i < nums.length; i++) {65             nums[i] = i+1;66         }67     }68     69     public void addFive(){70         for (int i = 0; i < nums.length; i++) {71             nums[i] = nums[i] + 5;72         }73     }74     75     public synchronized void print(){76         for (int i = 0; i < nums.length; i++) {77             System.out.print(nums[i] + " ");78         }79         80     }81     82     public int getLable(){//确定该由哪个线程打印83         return nums[4]/5%3;84     }85     public int getLastNum(){86         return nums[4];87     }88 }

线程1正在打印:1 2 3 4 5
线程2正在打印:6 7 8 9 10
线程3正在打印:11 12 13 14 15
线程1正在打印:16 17 18 19 20
线程2正在打印:21 22 23 24 25
线程3正在打印:26 27 28 29 30
线程1正在打印:31 32 33 34 35
线程2正在打印:36 37 38 39 40
线程3正在打印:41 42 43 44 45
线程1正在打印:46 47 48 49 50
线程2正在打印:51 52 53 54 55
线程3正在打印:56 57 58 59 60
线程1正在打印:61 62 63 64 65
线程2正在打印:66 67 68 69 70
线程3正在打印:71 72 73 74 75

多线程