RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
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线程才能运行。


名称栏目:J2EE线程代码示例
文章分享:http://www.jxjierui.cn/article/cciojgg.html