synchronized修饰代码块----代码演示
//synchronized锁解决线程安全问题
public class Test01 {
public static void main(String[] args) {
TestRunnable testRunnable1 = new TestRunnable();
TestRunnable testRunnable2 = new TestRunnable();
//创建线程,是公用的对象
Thread thread1 = new Thread(testRunnable1,"一号窗口");
Thread thread2 = new Thread(testRunnable2,"二号窗口");
thread1.start();
thread2.start();
}
}
class TestRunnable implements Runnable{
static int num=1;
//static String s = new String(); //对象锁
@Override
public void run() {
//添加锁,增加线程安全性
while (num<=1000){
//修饰代码块,该锁是一个固定值
synchronized ("锁"){
if (num<=1000){ //判断最后一张票数是否同时进行
System.out.println(Thread.currentThread().getName()+"---"+"票已经卖出"+num+"张");
num++;
}else {
System.out.println("票已经售空");
}
}
}
}
}
synchronized修饰普通方法----代码演示
//实现窗口买票的任务
public class Test02 {
public static void main(String[] args) {
//创建两个对象
TestTrack testTrack = new TestTrack();
//TestTrack testTrack1 = new TestTrack();
//创建线程对象
Thread thread = new Thread(testTrack,"窗口A");
Thread thread1 = new Thread(testTrack,"窗口B");
//开启线程
thread.start();
thread1.start();
}
}
class TestTrack implements Runnable{
static int num=1;
@Override
public void run() {
while (num <= 500) {
comm(); //同一个类中的方法是可以通过方法名()来获取该方法内容的
}
}
//修饰普通方法--this,表示的是当前对象,并且保证是同一个对象
public synchronized void comm(){
if (num<=500){
//Thread.currentThread().getName():设置线程的名字
System.out.println(Thread.currentThread().getName()+"卖出去了"+"--"+num+"张票");
}else {
System.out.println("票已售空");
}
num++;
}
}
synchronized修饰静态方法----代码演示
//实现窗口买票的任务
public class Test02 {
public static void main(String[] args) {
//创建两个对象
TestTrack testTrack = new TestTrack();
TestTrack testTrack1 = new TestTrack();
//创建线程对象
Thread thread = new Thread(testTrack,"窗口A");
Thread thread1 = new Thread(testTrack1,"窗口B");
//开启线程
thread.start();
thread1.start();
}
}
class TestTrack implements Runnable{
static int num=1;
@Override
public void run() {
while (num <= 500) {
comm1(); //同一个类中的方法是可以通过方法名()来获取该方法内容的
}
}
//修饰静态方法--Class,表示当前类,可以不保证同一个对象
public synchronized static void comm1(){
if (num<=500){
//Thread.currentThread().getName():设置线程的名字
System.out.println(Thread.currentThread().getName()+"卖出去了"+"--"+num+"张票");
}else {
System.out.println("票已售空");
}
num++;
}
}