什么是同步代码块
使用synchronize关键字加上锁对象来定义一段代码,这就叫同步代码块。
什么时候使用同步代码块
当多线程并发,有多段代码同时执行,如果希望一段代码在执行过程中多CPU不要切换到其他线程工作,这时就需要用到同步代码块。
示例
public class Demo1_Synchronized {
public static void main(String[] args) {
Printer p = new Printer();
new Thread(){
public void run(){
while(true){
p.print1();
}
}
}.start();
new Thread(){
public void run(){
while(true){
p.print2();
}
}
}.start();
}
}
class Printer{
Demo d = new Demo();
public void print1(){
synchronized(Printer.class) { // 同步代码块,锁机制,锁对象可以是任意的,但两条线程的锁对象要相同,括号中也可以传d
System.out.print("同");
System.out.print("步");
System.out.print("代");
System.out.print("码");
System.out.print("块");
System.out.println();
}
}
public void print2(){
synchronized(Printer.class){ // 锁对象不能用匿名对象,因为匿名对象不是同一个对象
System.out.print("s");
System.out.print("y");
System.out.print("n");
System.out.print("c");
System.out.print("h");
System.out.print("r");
System.out.print("o");
System.out.print("n");
System.out.print("i");
System.out.print("z");
System.out.print("e");
System.out.print("d");
System.out.println();
}
}
}
class Demo{}
同步方法
在方法上加synchronize关键字,就是同步方法。
非静态同步方法的锁对象是this
静态方法的锁对象是该类的字节码对象