当两个或多个线程访问同一资源时,需要以某种顺序来确保该资源在某一时刻只能被一个线程使用的方式叫做线程同步。
线程同步是为了防止同一资源同时被多个线程访问使用时造成的程序运行结果错误。
实现线程同步方法有两种,同步方法和同步代码块。
通过 synchronized关键字声明
同步方法:
访问修饰符 synchronized 返回类型 方法名(){}或
synchronized 访问修饰符 返回类型 方法名(){}
同步代码块:
synchronized(syncObject){
//所需同步代码块
}
线程间的通信方法
wait():挂起线程
notify():唤起线程
notifyAll():唤起所有被wait()方法阻塞的线程。
public class Book {
//创建共享资源 图书类
private String name;//图书名字
private double price;//图书价格
private boolean flag=true;
public Book() {
}
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public synchronized void set(String name,double price){
if(!flag){
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name;
this.price = price;
flag=false;
super.notify();
}
public synchronized void get(){
if(flag){
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(this.getName()+"--"+this.getPrice());
flag=true;
super.notify();
}
}
//创建一个图书馆线程 ,用来得到图书信息,销售图书
public class Library implements Runnable{
private Book book=null;
//标志位
private boolean flag=false;
public Library(Book book) {
this.book = book;
}
public void run(){
//得到图书信息,销售图书 ,两本书信息交替执行,
for(int i=1;i<=10;i++){
if(flag){ //flag=true时执行
this.book.set("《java》", 18);
flag=false;
}
if(!flag){
this.book.set("《MySQL》", 20);
flag=true;
}
}
}
}
public class Client implements Runnable{
private Book book=null;
public Client(Book book) {
this.book = book;
}
public void run(){
//得到图书信息,购买图书
for(int i=1;i<=10;i++){
this.book.get();
}
}
}
public class test {
//测试类
public static void main(String[] args) {
Book book=new Book();
Thread library =new Thread(new Library(book));
Thread client =new Thread(new Client(book));
library.start();
client.start();
}
}