多线程二


线程的互斥操作(解决多线程共享数据问题)
1. 同步块(保证某一段代码在某一时刻只能有一个线程访问) 

   锁(java中任何对象都是一把锁,有且只有一把钥匙)    

//同步函数,锁是this
public synchronized void f(){
  System.out.print("hello world");
}
 

2. 同步函数
        普通方法返回类型前加同步,锁就是当前对象
        静态方法的锁就是当前对象的类类型

//这就是代码块 锁作为参数这里以this为例
synchronized(this){
  System.out.print("hello world");
}



 3.多线程共享数据
public class Test1 {
	public static void main(String[] args) {
        //创建一个对象
		Output output = new Output();
        //创建两个线程
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true){
					output.print("hello");
				}
			}
		}).start();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true){
					output.print("world");
				}
			}
		}).start();
	}
}
class Output{
	public  void print(String name){
		/**
		 * 保证这段代码同时只有一个线程进来访问
		 * 一定要保证是同一个对象锁 这里用的是this(调用调用同步块的对象)
		 */
		synchronized (this) {
				for (int i = 0; i < name.length(); i++) {
				System.out.print(name.charAt(i));
			}
			System.out.println();
		}
	}
}


4.线程死锁
/**
* 第一个线程拿到a对象进入到第一个同步块
* 同时第二个线程拿到b对象第二个同步块
* 第一个线程等待第二个线程释放b
* 同时第二个线程等待第一个线程释放a
*/
synchronized(a){
  synchronized(b){
    System.out.print("hello");
  }
}
synchronized(b){
  synchronized(a){
    System.out.print("hello");
  }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值