J2EE线程代码示例

本篇文章提供了一段代码,展示了J2EE线程的开始,运行以及调用的方法。
首页 新闻资讯 行业资讯 J2EE线程代码示例

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

复制

public class TT implements Runnable {   int b = 100;      public synchronized void m1() throws Exception{    //Thread.sleep(2000);    b = 1000;    Thread.sleep(5000);    System.out.println("b = " + b);   }      public synchronized void m2() throws Exception {    Thread.sleep(2500);    b = 2000;    System.out.println( b);   }      public void run() {    try {     m1();    } catch(Exception e) {     e.printStackTrace();    }   }      public static void main(String[] args) throws Exception {    TT tt = new TT();    Thread t = new Thread(tt);    t.start();        tt.m2();    System.out.println(tt.b);   }  }
  • 1.

  • 2.

  • 3.

  • 4.

  • 5.

  • 6.

  • 7.

  • 8.

  • 9.

  • 10.

  • 11.

  • 12.

  • 13.

  • 14.

  • 15.

  • 16.

  • 17.

  • 18.

  • 19.

  • 20.

  • 21.

  • 22.

  • 23.

  • 24.

  • 25.

  • 26.

  • 27.

  • 28.

  • 29.

  • 30.

  • 31.

  • 32.

  • 33.

函数运行结果: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项目开发中的应用

20    2009-06-22 16:21:02    J2EE线程