J2EE线程代码示例

以下这段代码可以帮助你学习J2EE线程:

 
 
 
  1. public class TT implements Runnable {  
  2.  int b = 100;  
  3.    
  4.  public synchronized void m1() throws Exception{  
  5.   //Thread.sleep(2000);  
  6.   b = 1000;  
  7.   Thread.sleep(5000);  
  8.   System.out.println("b = " + b);  
  9.  }  
  10.    
  11.  public synchronized void m2() throws Exception {  
  12.   Thread.sleep(2500);  
  13.   b = 2000;  
  14.   System.out.println( b);  
  15.  }  
  16.    
  17.  public void run() {  
  18.   try {  
  19.    m1();  
  20.   } catch(Exception e) {  
  21.    e.printStackTrace();  
  22.   }  
  23.  }  
  24.    
  25.  public static void main(String[] args) throws Exception {  
  26.   TT tt = new TT();  
  27.   Thread t = new Thread(tt);  
  28.   t.start();  
  29.     
  30.   tt.m2();  
  31.   System.out.println(tt.b);  
  32.  }  

函数运行结果:2000
              2000
              b = 1000

函数分析:在main函数中,start了一个线程,即运行了该线程的run方法,run方法中要调用m1方法,而同时在main主线程中调用了m2的方法,注意此时m2锁定了对象,因此即使m2中有sleep方法,同样也要等m2结束后m1线程才能运行。

【编辑推荐】

  1. 结合struts和hibernate谈J2EE架构的数据表示
  2. .NET与J2EE之争
  3. J2ee Jdbc 存储过程调用
  4. j2ee应用与Bea.Weblogic Server
  5. 软件测试技术在J2EE项目开发中的应用
THE END