多线程实例

来源:互联网 发布:利淘网淘宝 编辑:程序博客网 时间:2024/05/23 22:58
  1. package proj_student;  
  2.   
  3. public class Test {  
  4.      // 采用 Runnable 接口方式创建的多条线程可以共享实例属性  
  5.   private int i=2;  
  6. //同步增加方法     
  7.     
  8.   private synchronized void inc(){     
  9.   
  10.      i ++;     
  11.   
  12.      System. out .println(Thread.currentThread().getName()+ "--inc:" + i );    
  13.   
  14.   }     
  15. //同步减算方法     
  16.     
  17.   private synchronized void dec(){     
  18.   
  19.      i --;     
  20.   
  21.      System. out .println(Thread.currentThread().getName()+ "--dec:" + i );    
  22.   
  23.   }     
  24.     
  25. //增加线程     
  26.     
  27.   class Inc implements Runnable {    
  28.   
  29.      public void run() {     
  30.   
  31.          inc();     
  32.   
  33.      }     
  34.   
  35.   }     
  36.     
  37.   // 减算线程     
  38.     
  39.   class Dec implements Runnable{    
  40.   
  41.      public void run() {     
  42.   
  43.          dec();     
  44.   
  45.      }     
  46.   
  47.   }     
  48.     
  49.   public static void main(String[] args) {  
  50.       Test t = new Test();     
  51.     // 内部类的实例化     
  52.       Inc inc = t.new Inc();  
  53.       Dec dec = t.new Dec();  
  54.         
  55.     // 创建 2*n 个线程 此处 n=2     
  56.       for ( int i = 0; i < 2; i++) {    
  57.             
  58.           new Thread(inc).start();     
  59.    
  60.           new Thread(dec).start();     
  61.    
  62.       }     
  63.         
  64. }  
  65.        
  66. }  
原创粉丝点击