线程问题

线程问题

线程锁为threadNo,每个线程threadNo唯一,达不到互斥最后资源recources不能同步

package len_server;

public class ThreadTest2 extends Thread {

  
	private  String threadNo;
	private  String lock;   

	private static int recources=100;//需要同步的资源对象   
 
	public ThreadTest2(String threadNo,String lock) {   
		this.threadNo = threadNo;  
		this.lock=lock;
	}   
	
	public static void main(String[] args) throws InterruptedException {
		for (int i = 1; i <=3; i++) {   
			ThreadTest2 t=new ThreadTest2(String.valueOf(i),"abc");
		    t.start();   
		 }
		sleep(2000);
		System.out.println("=================================");
		System.out.println(recources);//打印结果
	}
   
    public void run() {
    	
    	synchronized (this.getThreadNo()) {
    		int flag=recources;  //模拟查询余额
    		try {
				sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    		recources=flag+1;//模拟存款
		}
    	
    }
    
    

	public String getThreadNo() {
		return threadNo;
	}
	public void setThreadNo(String threadNo) {
		this.threadNo = threadNo;
	}
	public String getLock() {
		return lock;
	}
	public void setLock(String lock) {
		this.lock = lock;
	}
}

线程锁为lock,每个线程的lock相同,也就是锁对象相同能实现资源同步

package len_server;

public class ThreadTest2 extends Thread {

  
	private  String threadNo;
	private  String lock;   

	private static int recources=100;//需要同步的资源对象   
 
	public ThreadTest2(String threadNo,String lock) {   
		this.threadNo = threadNo;  
		this.lock=lock;
	}   
	
	public static void main(String[] args) throws InterruptedException {
		for (int i = 1; i <=3; i++) {   
			ThreadTest2 t=new ThreadTest2(String.valueOf(i),"abc");
		    t.start();   
		 }
		sleep(2000);
		System.out.println("=================================");
		System.out.println(recources);//打印结果
	}
   
    public void run() {
    	
    	synchronized (this.getLock()) {
    		int flag=recources;  //模拟查询余额
    		try {
				sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    		recources=flag+1;//模拟存款
		}
    	
    }
    
    

	public String getThreadNo() {
		return threadNo;
	}
	public void setThreadNo(String threadNo) {
		this.threadNo = threadNo;
	}
	public String getLock() {
		return lock;
	}
	public void setLock(String lock) {
		this.lock = lock;
	}
}

猜猜分别输出结果?

转载于:https://my.oschina.net/u/1377077/blog/803749

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值