syncronized是非公平锁,可重入锁
用法:
1.锁共享对象
2.静态同步方法:(其实锁的就是类对象)
3.同步代码块,锁类对象:
4.同步方法:(其实锁的就是this对象)
5.同步代码块,锁this对象
锁共享对象:
public class TrainThread extends Thread{
//初始化100张票,要定义为静态
private static int ticket = 100;
//定义了一个共享的对象,要定义为静态
private static Object obj = new Object();
public void run(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj){
while(ticket > 0){
System.out.println(Thread.currentThread().getName()+"卖出了第"+ (100 -ticket + 1)+"张票");
ticket --;
}
}
}
public static void main(String[] args) {
TrainThread thread1 = new TrainThread();
TrainThread thread2 = new TrainThread();
thread1.start();
thread2.start();
}
}
静态同步函数:(其实锁的就是类对象)
public class TrainThread2 extends Thread{
//初始化100张票,要定义为静态
private static int ticket = 100;
public void run(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
test();
}
//静态同步函数
private static synchronized void test() {
while(ticket > 0){
System.out.println(Thread.currentThread().getName()+"卖出了第"+ (100 -ticket + 1)+"张票");
ticket --;
}
}
public static void main(String[] args) {
TrainThread2 thread1 = new TrainThread2();
TrainThread2 thread2 = new TrainThread2();
thread1.start();
thread2.start();
}
}
锁类对象:
public class TrainThread3 extends Thread{
//初始化100张票,要定义为静态
private static int ticket = 100;
public void run(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//锁类对象
synchronized (TrainThread3.class){
while(ticket > 0){
System.out.println(Thread.currentThread().getName()+"卖出了第"+ (100 -ticket + 1)+"张票");
ticket --;
}
}
}
public static void main(String[] args) {
TrainThread3 thread1 = new TrainThread3();
TrainThread3 thread2 = new TrainThread3();
thread1.start();
thread2.start();
}
}
同步函数:(其实锁的就是this对象)
public class TrainRunnable2 implements Runnable{
//初始化100张票
private int ticket = 100;
public void run(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
test();
}
//同步函数
private synchronized void test() {
while(ticket > 0){
System.out.println(Thread.currentThread().getName()+"卖出了第"+ (100 -ticket + 1)+"张票");
ticket --;
}
}
public static void main(String[] args) {
TrainRunnable2 trainRunnable = new TrainRunnable2();
new Thread(trainRunnable).start();
new Thread(trainRunnable).start();
}
}
锁this对象:
public class TrainRunnable implements Runnable{
//初始化100张票
private int ticket = 100;
public void run(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this){
while(ticket > 0){
System.out.println(Thread.currentThread().getName()+"卖出了第"+ (100 -ticket + 1)+"张票");
ticket --;
}
}
}
public static void main(String[] args) {
TrainRunnable trainRunnable = new TrainRunnable();
new Thread(trainRunnable).start();
new Thread(trainRunnable).start();
}
}