·明确概念
- 线程同步:线程同步是指让多个线程按顺序执行(串行),而不是并行(默认情况)。
- java内置锁(包括同步锁):Java内置锁是一种互斥锁,通过同一个自定义的线程类开启的线程,不论开启几个,都只有一把锁。
先获得锁的线程先执行,当其执行完后会释放锁,该锁由其他线程获得并执行该线程。
·代码演示(运行结果,自行测试)
package com.imooc.demofirst;
/**
* 功能描述:使用同步锁synchronized,来实现代线程同步。
* @param:
* @Return:
* @Author: tongys
* @Date: 2019/9/29 14:18
*/
public class ThreadTest2 {
public static void main(String[] args) {
//java内置锁是一种互斥锁,通过同一个自定义的线程类开启的线程,不论开启几个,都只有一把锁。
// 先获得锁的线程先执行,当其执行完后会释放锁,该锁由其他线程获得并执行该线程。
//类锁
MyThread mt = new MyThread();
Thread td1 = new Thread(mt,"窗口A");
Thread td2 = new Thread(mt,"窗口B");
td1.start();
td2.start();
//对象锁
// MyThread2 mt2 = new MyThread2();
// Thread td1 = new Thread(mt2,"窗口A");
// Thread td2 = new Thread(mt2,"窗口B");
// td1.start();
// td2.start();
}
}
/**
* 功能描述:同步代码块之类锁
* @param:
* @Return:
* @Author: tongys
* @Date: 2019/9/29 14:18
*/
class MyThread implements Runnable{
int t = 5;
void sale(){
//需要设置一个锁定目标,可以锁定当前对象或类(对应对象锁和类锁),区别很大。
synchronized (MyThread.class){
if (t>0){
System.out.println(Thread.currentThread().getName()+":剩余"+(--t)+"张票");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void run() {
while(t >0){
sale();
}
}
}
/**
* 功能描述:同步方法之对象锁,在方法上加synchronized(隐式锁对象[this])
* @param:
* @Return:
* @Author: tongys
* @Date: 2019/9/29 14:53
*/
class MyThread2 implements Runnable{
int t = 5;
@Override
public void run() {
sale();
}
public synchronized void sale(){
while (t>0){
System.out.println(Thread.currentThread().getName()+":剩余"+(--t)+"张票");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 功能描述:同步代码块之对象锁(代码块对象锁)
* @param:
* @Return:
* @Author: tongys
* @Date: 2019/9/29 15:08
*/
class MyThread3 implements Runnable{
int t = 5;
void sale(){
synchronized (this){
while (t>0){
System.out.println(Thread.currentThread().getName()+":剩余"+(--t)+"张票");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void run() {
while(t>0){
sale();
}
}
}