1、线程同步
1.1、同步代码块
锁多条语句操作共享数据,可以使用同步代码块实现
synchonie(任意对象){
多条语句操作共享数据的代码
}
synchronie(任意对象):就相当于给代码加锁了,任意对象就可以看成是一把锁。
同步方法: 就是把synchronined关键字加到方法上
修饰符sychonred 返四值类型 方法名(方法参数){ }
同步方法的锁对象是什么呢?
同步静态方法 :就是synchronized以关键字加到静态方法
类名. class
package Demo01;
public class Demo01Ticket {
public static void main(String[] args) {
RunnableImpl run = new RunnableImpl()
Thread t0 = new Thread(run);
Thread t1 = new Thread(run);
Thread t2 = new Thread(run);
t0.start();
t1.start();
t2.start();
}
}
1
2
3
4
5
6
package Demo01;
public class RunnableImpl implements Runnable {
private int ticket = 100;
//Object obj = new Object();
@Override
public void run() {
while(true) {
payTicket();
}
}
public synchronized void payTicket() {
if(ticket>0) {
try {
Thread.sleep(1);
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->正在买第"+ticket+"张票");
ticket--;
}
}
}
1
2
3
4
5
6
7
8
9
v0id Lock ( ) :获得锁
void unlock ( ): 释放锁
LOCk是接口不能直接实倒化,这里采用它的实现类ReentrantLock来实倒化
Reentrantlocko :创建-个ReentrantLock的实例
Demo01Ticket {
public static void main(String[] args) {
RunnableImpl run = new RunnableImpl();
Thread t0 = new Thread(run);
Thread t1 = new Thread(run);
Thread t2 = new Thread(run);
t0.start();
t1.start();
t2.start();
}
}
1
2
3
4
5
6
package Demo02;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class RunnableImpl implements Runnable {
private int ticket = 10;
Lock l = new ReentrantLock();
@Override
public void run() {
while(true) {
l.lock();
if(ticket>0) {
try {
Thread.sleep(10);
System.out.println(Thread.currentThread().getName()+"-->正在买第"+ticket+"张票");
ticket--;
}catch (InterruptedException e) {
e.printStackTrace();
}finally {
l.unlock();
}
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
package Demo03;
public class Demo01WaitAndNotify {
public static void main(String[] args) {
Object obj = new Object();
new Thread() {
@Override
public void run() {
while(true) {
synchronized (obj) {
System.out.println("消费者1:告知老板包子的种类");
try {
obj.wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("包子好了!可以吃了");
System.out.println("=====================");
}
}
}
}.start();
new Thread() {
@Override
public void run() {
while(true) {
synchronized (obj) {
try {
//等待呼叫
obj.wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费者2:包子好了!来吃");
System.out.println("=====================");
}
}
}
}.start();
new Thread() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(3);
}catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj) {
System.out.println("生产者:老板花2秒做好了包子,呼叫顾客");
//obj.notify();//随机通知一个
obj.notifyAll();//通知所有的人
}
}
}
}.start();
}
}