多线程 小例子

 

synchronized    

     synchronized 关键字,代表这个方法加锁,相当于不管哪一个线程(例如线程A),运行到这个方法时,都要检查有没有其它线程B(或者C、 D等)正在用这个方法,有的话要等正在使用synchronized方法的线程B(或者C 、D)运行完这个方法后再运行此线程A;没有的话,直接运行。

 

下面是一个例子

方法1

 

public class RunThreads implements Runnable{
	
	public static void main(String[] args) {
		RunThreads runThreads=new RunThreads();
		
		new Thread(runThreads,"1-->").start();
		new Thread(runThreads,"2-->").start();
		new Thread(runThreads,"3-->").start();
	}
	public int tickets =5;
	public void run(){
		for (int i = 0; i < 50; i++) {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			synchronized (this) {
			if (tickets>0) {
				System.out.println("线程"+this.tickets--); 
			} 
		}
		}
	}
}


方法2

public class RunThreads1 implements Runnable{
	
	public static void main(String[] args) {
		RunThreads runThreads=new RunThreads();
		
		new Thread(runThreads,"1-->").start();
		new Thread(runThreads,"2-->").start();
		new Thread(runThreads,"3-->").start();
	}
	public int tickets =5;
	
	public synchronized void sall(){
		if (tickets>0) {
			System.out.println("线程"+this.tickets--); 
		} 
	}
	public void run(){
		for (int i = 0; i < 50; i++) {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			this.sall();
		}
		
	}
}


synchronized 方法用的多的话 会形成死锁

下面是一个例子

public class Zhangsan {
	
	public synchronized void say(Lisi ls){
		
		System.out.println(" 先-->  给钱");
		ls.give();
	}
	
	public synchronized void give(){ 
		
		System.out.println(" 给了钱  --> 放人 "); 
	}

}


 

public class Lisi {
	
	public synchronized void say(Zhangsan zs){
		
		System.out.println("先。。。。。。。。。。。。放人");
		zs.give();
	}

	public synchronized void give(){
		
		System.out.println("再。。。。。。。。给钱");
		
	}
}


 

public class DeadThreadss implements Runnable{    
	
	private Zhangsan zhangsan=new Zhangsan();     
	private Lisi lisi =new Lisi();
	
	public DeadThreadss(){       
		new Thread(this).start();  
		lisi.say(zhangsan);
	}
	public void run() {    
		zhangsan.say(lisi);
	} 
	public static void main(String[] args) {
		new DeadThreadss();
	}
}


运行上面的三个类 可实现死锁的  小例子

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值