java 线程同步synchronized详解的代码

在工作之余,将做工程过程中常用的内容片段记录起来,如下的内容是关于java 线程同步synchronized详解的内容,应该对各朋友也有用处。

package ths;
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();
}
}

结果:Asynchronizedloop0Asynchronizedloop1Asynchronizedloop2Asynchronizedloop3Asynchronizedloop4Bsynchronizedloop0Bsynchronizedloop1Bsynchronizedloop2Bsynchronizedloop3Bsynchronizedloop4二、然而,当一个线程访问object的一个synchronized(this)同步代码块时,另一个线程仍然可以访问该object中的非synchronized(this)同步代码块。

package ths;
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();
}
}

结果:t1:4t2:4t1:3t2:3t1:2t2:2t1:1t2:1t1:0t2:0三、尤其关键的是,当一个线程访问object的一个synchronized(this)同步代码块时,其他线程对object中所有其它synchronized(this)同步代码块的访问将被阻塞。

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

结果:t1:4t1:3t1:2t1:1t1:0t2:4t2:3t2:2t2:1t2:0四、第三个例子同样适用其它同步代码块。也就是说,当一个线程访问object的一个synchronized(this)同步代码块时,它就获得了这个object的对象锁。结果,其它线程对该object对象所有同步代码部分的访问都被暂时阻塞。

 public synchronized void m4t2() {  
      int i = 5;  
      while( i-- > 0) {  
           System.out.println(Thread.currentThread().getName() + " : " + i);  
           try {  
                Thread.sleep(500);  
           } catch (InterruptedException ie) {  
           }  
      }  
 }

结果:t1:4t1:3t1:2t1:1t1:0t2:4t2:3t2:2t2:1t2:0五、以上规则对其它对象锁同样适用:

package ths;
public class Thread3 {
class Inner {
private void m4t1() {
int i = 5;
while(i-- > 0) {
System.out.println(Thread.currentThread().getName() + " : Inner.m4t1()=" + i);
try {
Thread.sleep(500);
} catch(InterruptedException ie) {
}
}
}
private void m4t2() {
int i = 5;
while(i-- > 0) {
System.out.println(Thread.currentThread().getName() + " : Inner.m4t2()=" + i);
try {
Thread.sleep(500);
} catch(InterruptedException ie) {
}
}
}
}
private void m4t1(Inner inner) {
inner.m4t1();
}
private void m4t2(Inner inner) {
inner.m4t2();
}
public static void main(String[] args) {
final Thread3 myt3 = new Thread3();
final Inner inner = myt3.new Inner();
Thread t1 = new Thread( new Runnable() {public void run() { myt3.m4t1(inner);} }, “t1”);
Thread t2 = new Thread( new Runnable() {public void run() { myt3.m4t2(inner);} }, “t2”);
t1.start();
t2.start();
}
}

结果:尽管线程t1获得了对Inner的对象锁,但由于线程t2访问的是同一个Inner中的非同步部分。所以两个线程互不干扰。t1:Inner.m4t1()=4t2:Inner.m4t2()=4t1:Inner.m4t1()=3t2:Inner.m4t2()=3t1:Inner.m4t1()=2t2:Inner.m4t2()=2t1:Inner.m4t1()=1t2:Inner.m4t2()=1t1:Inner.m4t1()=0t2:Inner.m4t2()=0现在在Inner.m4t2()前面加上synchronized:

 private synchronized void m4t2() {  
      int i = 5;  
      while(i-- > 0) {  
           System.out.println(Thread.currentThread().getName() + " : Inner.m4t2()=" + i);  
           try {  
                Thread.sleep(500);  
           } catch(InterruptedException ie) {  
           }  
      }  
 }

public class TextThread {
public static void main(String[] args) {
TxtThread tt = new TxtThread();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
}
}
class TxtThread implements Runnable {
int num = 100;
String str = new String();
public void run() {
synchronized (str) {
while (num > 0) {
try {
Thread.sleep(1);
} catch (Exception e) {
e.getMessage();
}
System.out.println(Thread.currentThread().getName()
+ "this is " + num–);
}
}
}
}

public void methodAAA()
{
{
}
}

(1)处的this指的是什么呢?它指的就是调用这个方法的对象,如P1。可见同步方法实质是将synchronized作用于objectreference。――那个拿到了P1对象锁的线程,才可以调用P1的同步方法,而对P2而言,P1这个锁与它毫不相干,程序也可能在这种情形下摆脱同步机制的控制,造成数据混乱:(2.同步块,示例代码如下:

public void method3(SomeObject so)
{
synchronized(so)
{
}
}

这时,锁就是so这个对象,谁拿到这个锁谁就可以运行它所控制的那段代码。当有一个明确的对象作为锁时,就可以这样写程序,但当没有明确的对象作为锁,只是想让一段代码同步时,可以创建一个特殊的instance变量(它得是一个对象)来充当锁:

class Foo implements Runnable
{
Public void methodA()
{
}
}

注:零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码:生成零长度的byte[]对象只需3条操作码,而Objectlock=newObject()则需要7行操作码。3.将synchronized作用于static函数,示例代码如下:

Class Foo
{
{
}
public void methodBBB()
{
}
}

代码中的methodBBB()方法是把classliteral作为锁的情况,它和同步的static函数产生的效果是一样的,取得的锁很特别,是当前调用这个方法的对象所属的类(Class,而不再是由这个Class产生的某个具体对象了)。记得在《EffectiveJava》一书中看到过将Foo.class和P1.getClass()用于作同步锁还不一样,不能用P1.getClass()来达到锁这个Class的目的。P1指的是由Foo类产生的对象。可以推断:如果一个类中定义了一个synchronized的static函数A,也定义了一个synchronized的instance函数B,那么这个类的同一对象Obj在多线程中分别访问A和B两个方法时,不会构成同步,因为它们的锁都不一样。A方法的锁是Obj这个对象,而B的锁是Obj所属的那个Class。小结如下:搞清楚synchronized锁定的是哪个对象,就能帮助我们设计更安全的多线程程序。还有一些技巧可以让我们对共享资源的同步访问更加安全:1.定义private的instance变量+它的get方法,而不要定义public/protected的instance变量。如果将变量定义为public,对象在外界可以绕过同步方法的控制而直接取得它,并改动它。这也是JavaBean的标准实现方式之一。2.如果instance变量是一个对象,如数组或ArrayList什么的,那上述方法仍然不安全,因为当外界对象通过get方法拿到这个instance对象的引用后,又将其指向另一个对象,那么这个private变量也就变了,岂不是很危险。这个时候就需要将get方法也加上synchronized同步,并且,只返回这个private对象的clone()――这样,调用端得到的就是对象副本的引用了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值