线程同步
两种方式:使用 同步代码块、同步方法
什么情况下需要同步?
当多线程并发, 有多段代码同时执行时, 我们希望某一段代码执行的过程中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("件");
}
}
}
}
本文深入探讨了线程同步的重要性,详细解析了同步代码块和同步方法的使用,以及如何通过synchronized关键字确保多线程环境下的数据安全。文章通过具体示例展示了不同锁对象的应用,帮助读者理解线程同步的基本原理。

被折叠的 条评论
为什么被折叠?



