public class TT implements Runnable {
int b = 100;
public synchronized void m1() throws Exception{
//Thread.sleep(2000);
System.out.println("m1()ing");
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception {
System.out.println("m2()ing");
Thread.sleep(2500);
b = 2000;
}
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);
}
}这段代码的运行结果是:m2()ing
2000
m1()ing
b=1000
把m2()前边的synchronized去掉后public class TT implements Runnable {
int b = 100;
public synchronized void m1() throws Exception{
//Thread.sleep(2000);
System.out.println("m1()ing");
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public void m2() throws Exception {
System.out.println("m2()ing");
Thread.sleep(2500);
b = 2000;
}
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);
}
}结果中b=2000了
我知道synchronized的作用是当某一线程访问带有该关键字的方法时,可以保证某一时刻只有一个线程访问该方法,其他的必须等这个线程执行完了以后才可以(即获得了索),但是在第一个程序中明明m1()和m2()是两个不同的线程去访问的,m1()是t线程访问的,m2()是主线程main()访问的,我觉得他们之前的synchronized其实是形同虚设的,因为这个关键字只保证访问同一个方法时候是互斥的,但是这里明明是两个不同的方法m1()和m2()
int b = 100;
public synchronized void m1() throws Exception{
//Thread.sleep(2000);
System.out.println("m1()ing");
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception {
System.out.println("m2()ing");
Thread.sleep(2500);
b = 2000;
}
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);
}
}这段代码的运行结果是:m2()ing
2000
m1()ing
b=1000
把m2()前边的synchronized去掉后public class TT implements Runnable {
int b = 100;
public synchronized void m1() throws Exception{
//Thread.sleep(2000);
System.out.println("m1()ing");
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public void m2() throws Exception {
System.out.println("m2()ing");
Thread.sleep(2500);
b = 2000;
}
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);
}
}结果中b=2000了
我知道synchronized的作用是当某一线程访问带有该关键字的方法时,可以保证某一时刻只有一个线程访问该方法,其他的必须等这个线程执行完了以后才可以(即获得了索),但是在第一个程序中明明m1()和m2()是两个不同的线程去访问的,m1()是t线程访问的,m2()是主线程main()访问的,我觉得他们之前的synchronized其实是形同虚设的,因为这个关键字只保证访问同一个方法时候是互斥的,但是这里明明是两个不同的方法m1()和m2()
m2()ing
m1()ing
2000
b=1000
有时却是 m2()ing
2000
m1()ing
b=1000
带有synchronized关键字的方法在执行时需要获得所在对象锁,因此如果你的多个线程调用的是同一个对象的m1和m2方法,那么他们都试图获得该对象的锁,所以m1和m2之间也是互斥的。
有些地方并不恰当