synchronized 修饰方法

来源:互联网 发布:自助建站 源码 编辑:程序博客网 时间:2024/06/11 16:42
public class Thread3{ public static void main(String[] args)throws Exception{  TT t1 = new TT();  Thread tt = new Thread(t1);  tt.start();  t1.m2();  System.out.println("t1.i =  "+t1.i); }}class TT implements Runnable{ int i = 100; public synchronized void m1(){    try{   i=200;   Thread.sleep(5000);   System.out.println("m1:i = "+i);  }catch(InterruptedException ie){   ie.printStackTrace();  } }  public synchronized  void m2() throws Exception{  i=300;  Thread.sleep(2000);  System.out.println("m2:i = "+i); }  public void run(){  m1(); }}方法m2()前加synchronized和不加的运行顺序有什么区别,i的值是怎么变化的
以上是问题
下面是问题回答
这个synchronized其实是一个线程锁,在保持数据同步上起到很到作用。你现在的状况 我猜你只要记住就行了  你暂时不用接触这些下面是关于synchronized的一些理解吧!一、当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。   二、当一个线程访问object的一个synchronized(this)同步代码块时,其他线程对object中所有其它synchronized(this)同步代码块的访问将被阻塞。   三、然而,当一个线程访问object的一个synchronized(this)同步代码块时,另一个线程仍然可以访问该object中的除synchronized(this)同步代码块以外的部分。   四、第三个例子同样适用其它同步代码块。也就是说,当一个线程访问object的一个synchronized(this)同步代码块时,它就获得了这个object的对象锁。结果,其它线程对该object对象所有同步代码部分的访问都被暂时阻塞。   五、以上规则对其它对象锁同样适用========================i值的传输===============解析main函数的代码块TT t1 = new TT();  Thread tt = new Thread(t1);  tt.start();  t1.m2();  System.out.println("t1.i =  "+t1.i);TT t1 = new TT();//很简单 初始化这个TT类。但这个TT是继承了Runnable接口的类。并且实现了Runnable的run方法。Thread tt = new Thread(t1);//实例化一个线程实例。并将TT类的句柄传给这个线程。 tt.start();//启动线程,这个就是启动tt类中的run方法。但和直接运行run方法不一样。记住这点。start()代表这个线程启动了。就开始运行线程里的方法 public void run(){  m1(); }这个  然后这个方法去调用m1()方法。*********================= int i = 100; public synchronized void m1(){    try{   i=200;   Thread.sleep(5000);   System.out.println("m1:i = "+i);  }catch(InterruptedException ie){   ie.printStackTrace();  }虽然int i = 100;但try里面给i赋值了。现在的i =200;Thread.sleep(5000);线程睡了5秒的觉System.out.println("m1:i = "+i);//然后打印了i的值 。这个i等于200;所以打印出200;============================= 再看 t1.m2();他是通过TT句柄方法m2()方法。这个你应该理解吧!运行m2()方法============================ public synchronized  void m2() throws Exception{  i=300;  Thread.sleep(2000);  System.out.println("m2:i = "+i); }i=300;给i赋值,所以i等于300 Thread.sleep(2000);线程睡了2秒觉。System.out.println("m2:i = "+i);醒来后打印了个300===========================最后一句System.out.println("t1.i =  "+t1.i);这个地方就看t1.i(加好后面的,前面只是字符串),这个就是直接调用TT里的变量i 这个时候的i被修改了编程300了 所以是300.