`
shengren0
  • 浏览: 21501 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

java synchronized关键字

阅读更多

synchronized用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码。

 

需要注意的问题有:

  1. 当多个并发线程访问同一个对象实例的synchronized代码块时,只有一个线程能够执行这个代码块,只有当前线程运行结束后,其他线程才可以执行这个代码块。
  2. 当一个线程访问一个对象实例的synchronized代码块时,其他线程仍然可以访问该对象实例中其他非synchronized代码块。
  3. 当一个线程访问一个对象实例的synchronized代码块时,其他线程对该对象实例中的所有synchronized代码块的访问都将被阻塞。
  4. 当一个线程访问一个对象实例的synchronized代码块时,该线程也就获得了这个对象实例的对象锁,所以其他线程对该对象实例中的synchronized代码块的访问就被阻塞了

public class Thread1 implements Runnable { 
     public void run() { 
          synchronized(this) { 
               for (int i = 0; i < 5; i++) { 
                    System.out.println(Thread.currentThread().getName() + " synchronized loop " + i); 
               } 
          } 
     } 
     public static void main(String[] args) { 
          Thread1 t1 = new Thread1(); 
          Thread ta = new Thread(t1, "A"); 
          Thread tb = new Thread(t1, "B"); 
          ta.start(); 
          tb.start(); 
     }
}
 
public class Thread2 { 
     public void m4t1() { 
          synchronized(this) { 
               int i = 5; 
               while( i-- > 0) { 
                    System.out.println(Thread.currentThread().getName() + " : " + i); 
                    try { 
                         Thread.sleep(500); 
                    } catch (InterruptedException ie) { 
                    } 
               } 
          } 
     } 
     public void m4t2() { 
          int i = 5; 
          while( i-- > 0) { 
               System.out.println(Thread.currentThread().getName() + " : " + i); 
               try { 
                    Thread.sleep(500); 
               } catch (InterruptedException ie) { 
               } 
          } 
     } 
     public static void main(String[] args) { 
          final Thread2 myt2 = new Thread2(); 
          Thread t1 = new Thread(  new Runnable() {  public void run() {  myt2.m4t1();  }  }, "t1"  ); 
          Thread t2 = new Thread(  new Runnable() {  public void run() { myt2.m4t2();   }  }, "t2"  ); 
          t1.start(); 
          t2.start(); 
     }
}
 
public class Thread3 {
	public void m4t1() {
		synchronized (this) {
			int i = 5;
			while (i-- > 0) {
				System.out
						.println(Thread.currentThread().getName() + " : " + i);
			}
		}
	}

	public void m4t2() {
		synchronized (this) {
			int i = 5;
			while (i-- > 0) {
				System.out
						.println(Thread.currentThread().getName() + " : " + i);
			}
		}
	}

	public static void main(String[] args) {
		final Thread3 myt3 = new Thread3();
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				myt3.m4t1();
			}
		}, "t1");
		Thread t2 = new Thread(new Runnable() {
			public void run() {
				myt3.m4t2();
			}
		}, "t2");
		t1.start();
		t2.start();
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics