public class TT implements Runnable{
int b = 100;
public synchronized void m1()throws Exception
{
b = 1000;
Thread.sleep(3000);
System.out.println("b = " + b);
}
public synchronized void m2() throws InterruptedException
{
b = 2000;
Thread.sleep(1500);
}
public void run()
{
try
{
m1();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException
{
TT t = new TT();
Thread tt = new Thread(t);
tt.start();
Thread.sleep(2000);
t.m2();
System.out.println(t.b);
}
}
为什么第一个输出的b是等于1000而不是2000呢?
在System.out.println("b = " + b)这句话执行的时候,m2()方法不是已经把b改成2000了吗?
谁能给我详细的解释下吗?谢~~~
int b = 100;
public synchronized void m1()throws Exception
{
b = 1000;
Thread.sleep(3000);
System.out.println("b = " + b);
}
public synchronized void m2() throws InterruptedException
{
b = 2000;
Thread.sleep(1500);
}
public void run()
{
try
{
m1();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException
{
TT t = new TT();
Thread tt = new Thread(t);
tt.start();
Thread.sleep(2000);
t.m2();
System.out.println(t.b);
}
}
为什么第一个输出的b是等于1000而不是2000呢?
在System.out.println("b = " + b)这句话执行的时候,m2()方法不是已经把b改成2000了吗?
谁能给我详细的解释下吗?谢~~~
t.m2();只能在等待 因为synchronized锁的关系 然后当tt执行到System.out.println("b = " + b);
最后才是 t.m2();
public synchronized void m1()throws Exception
{
System.out.println("m1开始执行");
b = 1000;
Thread.sleep(3000);
System.out.println("b = " + b);
}
public synchronized void m2() throws InterruptedException
{
System.out.println("m2开始执行");
b = 2000;
Thread.sleep(1500);
}
运行结果是:
m1开始执行
b = 1000
m2开始执行
2000
“b = 1000”输出以后,才输出的“m2开始执行”,这样就知道是 m1 执行完了才执行 m2的
b=2000了呢?
public synchronized void m1(){}; == public void m1() {synchronized(this) {}}
一个对象中经过synchronized 限制的多个方法中,同时进行的线程只有一个呢?
public static void main(String[] args) throws InterruptedException
{
TT t = new TT();
Thread tt = new Thread(t);
tt.start();
Thread.sleep(2000);
t.m2();
System.out.println(t.b);
}
[/Quote]从这里开始分析,main线程开始执行,到tt.star()时tt这个线程就开始执行你重写的run()方法,run()方法中调用m1(),m1()声明为synchronized,tt这个线程就获得TT 这个对象的锁,但是在没有执行完之前(虽然有睡眠)但是不会放弃这个对象的锁,其他的线程就不能访问该对象其他的synchronized方法,只有等tt这个线程结束以后才能访问,但是其他的线程可以访问这个对象中非synchronized的方法,(也就是你把m2()的synchronized去掉以后的解释)。以下的代码是在你代码的基础上的一点改变,你看哈行不?
public class Test implements Runnable{
int b = 100;
public synchronized void m1()throws Exception
{
b = 1000;
Thread.sleep(1000);
System.out.println("b = " + b);
}
public void m2() throws InterruptedException
{
b = 2000;
//Thread.sleep(1500);
}
public void run()
{
try
{
m1();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException
{
Test t = new Test();
Thread tt = new Thread(t);
tt.start();
t.m2();
Thread.sleep(1000);
System.out.println(t.b);
}
}