多线程练习(java)

时间:2022-12-29 18:00:07
 1 public class TestThread
 2 {
 3     public static void main(String[] args)
 4     {
 5         RandomNumber r=new RandomNumber();
 6         
 7         Thread1 t1=new Thread1(r);
 8         Thread2 t2=new Thread2(r);
 9         
10         Thread thread1=new Thread(t1);
11         Thread thread2=new Thread(t2);
12         
13         thread1.start();
14         thread2.start();
15     }
16 }
 1 public class RandomNumber
 2 {
 3     public int i;
 4     public int num[];
 5     
 6     RandomNumber()
 7     {
 8         i=(int)(Math.random()*100)+11;
 9         num=new int[i];
10         
11         for (int j=0;j<i;j++)
12         {
13             num[j]=(int)(Math.random()*100);
14         }
15     }
16 }
 1 //public class Thread1 extends Thread {  
 2 public class Thread1 implements Runnable { 
 3       
 4     private int Thread1[];  
 5     Thread1(RandomNumber rn)  
 6     {  
 7         //Thread1 = new int[rn.i];   
 8         Thread1 = rn.num;  
 9     }  
10     public void run()  
11     {  
12         for(int i=0; i<Thread1.length; i++)  
13         {  
14             for(int j=0; j<Thread1.length-i-1; j++)  
15             {  
16                 if(Thread1[j] > Thread1[j+1])  
17                 {  
18                     int mid = Thread1[j];  
19                     Thread1[j] = Thread1[j+1];  
20                     Thread1[j+1] = mid;  
21                 }  
22             }  
23         }  
24         for(int i=0; i<Thread1.length; i++)  
25         {  
26             System.out.println(Thread1[i]);  
27         }  
28         System.out.println("Thread1打印完成。");  
29     }  
30 }  
 1 import java.util.Arrays;  
 2   
 3 public class Thread2 implements Runnable {  
 4       
 5     private int Thread2[];  
 6     Thread2(RandomNumber rn)  
 7     {  
 8        // Thread2 = new int[rn.num.length];   
 9         Thread2 = rn.num;  
10     }  
11   
12   public void run()
13   {
14       Arrays.sort(Thread2);
15       for (int i=0;i<Thread2.length;i++)
16       {
17           System.out.println(Thread2[i]);
18       }
19       System.out.println("Thread2打印完成");
20   }
21 }