java:synchronized有个什么用啊?看这个
publicclassTTimplementsRunnable{intb=100;publicsynchronizedvoidm1()throwsException{//...
public class TT implements Runnable {
int b = 100;
public synchronized void m1() throws Exception{ //去掉synchronized,运行结果不变,到底synchronized有什么用途?
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception {
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();
Thread.sleep(1000);
tt.m2();
}
}
public synchronized void m2() throws Exception 这句中的synchronized应该去掉才是我要发布的代码。最后运行结果为:1000 b=1000 展开
int b = 100;
public synchronized void m1() throws Exception{ //去掉synchronized,运行结果不变,到底synchronized有什么用途?
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception {
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();
Thread.sleep(1000);
tt.m2();
}
}
public synchronized void m2() throws Exception 这句中的synchronized应该去掉才是我要发布的代码。最后运行结果为:1000 b=1000 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询