62,623
社区成员
发帖
与我相关
我的任务
分享package com.xuz.csdn.july11;
public class TT implements Runnable {
int b = 100;
public synchronized void m1() throws Exception {
System.out.println("m1");
b = 1000;
System.out.println("in m1 sleep before b = " + b);
Thread.sleep(5000);
System.out.println("in m1 sleep after b = " + b);
System.out.println("b= " + b);
}
public void m2() throws Exception {
System.out.println("m2");
System.out.println("in m2 sleep before b = " + b);
Thread.sleep(2500);
b = 2000;
System.out.println("in m2 sleep after b = " + 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();
}
}
public class TT implements Runnable {
int b = 100;
boolean isDone;
public synchronized void m1() throws Exception {
while(!isDone);
b = 1000;
Thread.sleep(5000);
System.out.println("b= " + b);
}
public void m2() throws Exception {
Thread.sleep(2500);
b = 2000;
isDone = true;
}
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();
}
}
public static void main(String [] args) throws Exception {
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
}
}
这里先执行m2,再执行m1()的可能性比较大。
[code=Java]
public synchronized void m1() throws Exception {
System.out.println("进入m1");
b = 1000;
Thread.sleep(5000);
System.out.println("b= " + b);
}
public void m2() throws Exception {
System.out.println("进入m2");
Thread.sleep(2500);
b = 2000;
}