Java 线程同步

同步代码块:在代码块前加上“synchronized”关键字,则称此代码块为同步代码块
格式:
    synchronized(同步对象){
        需要同步的代码块
    }
同步方法:方法也可以同步
格式:
    synchronized void 方法名(){}


同步代码块:

class MyThreadDemo implements Runnable {
	private int ticket=5;
	public void run() {
		for (int i = 0; i < 10; i++) {
			if (ticket>0) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("车票:"+ticket--);
			}
		}
	}
}
public class ThreadDemo04 {

	public static void main(String[] args) {
		MyThreadDemo m=new MyThreadDemo();
		Thread t1=new Thread(m);
		Thread t2=new Thread(m);
		Thread t3=new Thread(m);
		
		t1.start();
		t2.start();
		t3.start();
	}

}

 输出:

车票:5
车票:3
车票:4
车票:2
车票:0
车票:1

 车票应该从大到小递减的,说明程序执行过程中run方法里的代码块没有同步。

加入同步:

class MyThreadDemo implements Runnable {
	private int ticket=5;
	public void run() {
		for (int i = 0; i < 10; i++) {
			synchronized (this) {
				if (ticket>0) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("车票:"+ticket--);
				}
			}
			
		}
	}
}
public class ThreadDemo04 {

	public static void main(String[] args) {
		MyThreadDemo m=new MyThreadDemo();
		Thread t1=new Thread(m);
		Thread t2=new Thread(m);
		Thread t3=new Thread(m);
		
		t1.start();
		t2.start();
		t3.start();
	}

}

 输出:

车票:5
车票:4
车票:3
车票:2
车票:1

同步方法:

class MyThreadDemo implements Runnable {
	private int ticket=5;
	public void run() {
			tell();
	}
	public synchronized void tell() {
		for (int i = 0; i < 10; i++) {
			if (ticket>0) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("车票:"+ticket--);
		}
		}
	}
}
public class ThreadDemo04 {

	public static void main(String[] args) {
		MyThreadDemo m=new MyThreadDemo();
		Thread t1=new Thread(m);
		Thread t2=new Thread(m);
		Thread t3=new Thread(m);
		
		t1.start();
		t2.start();
		t3.start();
	}

}

 输出同上。

原文地址:https://www.cnblogs.com/zhhy236400/p/10490919.html