JAVA高级基础(67)---线程同步

本文深入探讨了线程同步的重要性,详细解析了同步代码块和同步方法的使用,以及如何通过synchronized关键字确保多线程环境下的数据安全。文章通过具体示例展示了不同锁对象的应用,帮助读者理解线程同步的基本原理。

线程同步

两种方式:使用 同步代码块、同步方法   

什么情况下需要同步?

当多线程并发, 有多段代码同时执行时, 我们希望某一段代码执行的过程中CPU不要切换到其他线程工作. 这时就需要同步.

如果两段代码是同步的, 那么同一时间只能执行一段, 在一段代码没执行结束之前, 不会执行另外一段代码.   

多线程安全问题的原因(也是我们以后判断一个程序是否有线程安全问题的依据)

A:是否是多线程环境

B:是否有共享数据

C:是否有多条语句操作共享数据

同步代码块

使用 synchronized  关键字加上一个锁对象来定义一段代码,这就叫同步代码块。多个同步代码块如果使用相同的锁对象,那么他们就是同步的。

同步代码块中:

锁对象,可以是任意对象,需要保证在多个同步代码块中使用的是同一个锁对象。this也可作为锁对象,但是不能在线程run方法中的同步代码块中使用this   

package org.lanqiao.thread.demo;

public class TheadDemo {
	
	public static void main(String[] args) {
		//ThreadDemo td = new ThreadDemo();
		//Object obj = new Object();
		//String str = new String();
		Thread t1 = new Thread() {	
			public void run() {
				synchronized(this) {
					System.out.print("太");
					System.out.print("原");
					System.out.print("师");
					System.out.print("范");
				}
				
				
			}
			
		};
		Thread t2 = new Thread() {
			public void run() {
				synchronized (this) {
					System.out.print("蓝");
					System.out.print("桥");
					System.out.print("软");
					System.out.print("件");
				}
				
				
			}
			
		};
		t1.start();
		t2.start();
	}
	
	
	
}

同步方法

使用 synchronized  关键字修饰一个方法,该方法中所有的代码都是同步的。锁对象:this 本类的当前对象。

静态方法的同步

静态同步方法中的锁对象:本类的Class对象

package org.lanqiao.thread.demo;

public class TreadDemo2 {
	
	public static void main(String[] args) {
		Print p = new Print();
		new Thread() {
			public void run() {
				Print.print1();
				
			}
			
		}.start();
		
		new Thread() {
			
			public void run() {
				Print.print2();
			}
		}.start();
		
	}
	
	
	
	
	
	
}
class Print{
	
	public static  synchronized void print1() {
			for(int i = 0 ; i < 10 ; i ++) {
				System.out.print("太");
				System.out.print("原");
				System.out.print("师");
				System.out.print("范");
				System.out.println();
			}
		
		
		
		
	}
	
	public static  void print2() {
		synchronized(Print.class) {
			for(int i = 0 ; i < 10 ; i ++) {
				System.out.print("蓝");
				System.out.print("桥");
				System.out.print("软");
				System.out.println("件");
			}
		}
			
		
	}
	
}


   

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值