java锁机制

原文:http://blog.csdn.net/yangzhijun_cau/article/details/6432216


线程的同步问题:

      

        1.给要同步的方法前边加上关键字synchronized

        2.最好准确到粒度,就要给要同步的代码块加上synchronized块

        3.同步问题解决了,但是若要考虑到同步安全问题的话,就要考虑并发性


所以要有锁,其实现为 一、给要同步的方法前面加上锁,String lock = new String("lock");                 

                                               二、将要同步的代码块变成静态的static


代码如下所附:


1.如下为上边的1:

 public class ThreadTest extends Thread {

    private int threadNo;

    public ThreadTest(int threadNo) {
        this.threadNo = threadNo;
    }
    
    public static void main(String[] args) throws Exception {   
        for (int i = 1; i < 10; i++) {   
           new ThreadTest(i).start();  
            Thread.sleep(1);   
        }   
     }   
    
    @Override  
     public synchronized void run() {   
        for (int i = 1; i < 10000; i++) {   
            System.out.println("No." + threadNo + ":" + i);   
        }   
     }
}


2.如下为上边的2:

public class ThreadTest1 extends Thread {

    private int threadNo;
    private String lock;  
    
    public ThreadTest1(int threadNo, String lock) {   
         this.threadNo = threadNo;   
         this.lock = lock;  
         }
    
    public static void main(String[] args) throws Exception {   
       String lock = new String("lock");   
         for (int i = 1; i < 10; i++) {     
             new ThreadTest1(i, lock).start();   
             Thread.sleep(1);   
         }   
      }
                
    public void run() {     
     synchronized (lock) {   
          for (int i = 1; i < 10000; i++) {   
           System.out.println("No." + threadNo + ":" + i);   
        }      
     }     
     }   
}


3.如下为上边的3:

public class ThreadTest2 extends Thread {
    private int threadNo;   

    public ThreadTest2(int threadNo) {   
        this.threadNo = threadNo;   
    }   

    public static void main(String[] args) throws Exception {   
        for (int i = 1; i < 20; i++) {   
            new ThreadTest2(i).start();   
            Thread.sleep(1);   
        }   
    }   

    public static synchronized void abc(int threadNo) {   
        for (int i = 1; i < 10000; i++) {   
            System.out.println("No." + threadNo + ":" + i);           
        }   
    }   

    public void run() {   
        abc(threadNo);   
    }

}


注:start()方法为开启线程;run()为线程要执行的方法。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值