java:多线程(同步方法)

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq_24644517/article/details/84578465

使用synchronized关键字修饰一个方法, 该方法中所有的代码都是同步的

import javax.swing.plaf.synth.SynthSpinnerUI;

public class Demo2_Synchronized {

	public static void main(String[] args) {
		Printer2 p=new Printer2();//1.8之前,匿名内部类如果要使用局部变量,被使用的变量 要被final修饰
		new Thread() {
			public void run() {
				while(true) {
					p.print1();
				}
			}
		}.start();
		
		
		new Thread() {
			public void run() {
				while(true) {
					p.print2();
				}
			}
		}.start();
	}

}

class Printer2{
	Demo d=new Demo();
	//非静态的同步方法锁对象是什么?
	//非静态的同步方法的锁对象是this
	//静态的同步方法的锁对象是什么?
	//是该类的字节码对象
	public static synchronized void print1() {//同步方法只需要在方法加上synchronized关键字即可
		
			System.out.println("同步");
			System.out.println("代码块");
			System.out.println("1");
		}
		

	
	public static synchronized void print2() {//同步方法只需要在方法加上synchronized关键字即可
//		synchronized(this) {//对象本身
		synchronized(Printer2.class) {//字节码对象

			System.out.println("同步2");
			System.out.println("代码2");
			System.out.println("2");
		}
		}
}

猜你喜欢

转载自blog.csdn.net/qq_24644517/article/details/84578465