以下这段代码可以帮助你学习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线程才能运行。
【编辑推荐】