62,625
社区成员
发帖
与我相关
我的任务
分享
public class TT implements Runnable {
int b = 100;
int i = 0;
public synchronized void m1() throws Exception {
System.out.println(Thread.currentThread().getName()+"线程进入m1");
b = 1000;
Thread.sleep(5000);
i++;
System.out.println("m1.b="+ b +",i=" + i+"线程是:" + Thread.currentThread().getName());
System.out.println("结束m1");
}
public synchronized void m2() throws Exception {
System.out.println(Thread.currentThread().getName()+"线程进入m2");
Thread.sleep(2500);
b = 2000;
System.out.println("m2.b=" + b +",i="+ i+"线程是:"+ Thread.currentThread().getName());
}
public void run() {
try {
System.out.println(Thread.currentThread().getName()+"开始执行run方法");
m1();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName()+"执行run方法完毕");
}
}
public static void main(String[] args) throws Exception {
TT tt = new TT();
Thread t1 = new Thread(tt);
t1.setName("线程1");
t1.start();
tt.m1();
// main线程进入m1
// 线程1开始执行run方法
// m1.b=1000,i=1线程是:main
// 结束m1
// 线程1线程进入m1
// m1.b=1000,i=2线程是:线程1
// 结束m1
// 线程1执行run方法完毕
// tt.m2();
// System.out.println(tt.b);
// main线程进入m2
// 线程1开始执行run方法
// m2.b=2000,i=0线程是:main
// 线程1线程进入m1
// m1.b=1000,i=1线程是:线程1
// 结束m1
// 线程1执行run方法完毕
}
}这个是上面的运行结果,可以看看