多线程安全卖票问题
package com.atjava.test;
class WindowRun implements Runnable{
private int ticket = 100;
@Override
public void run() {
while (true){
if(ticket > 0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖票,票号为:" + ticket);
ticket--;
}else {
break;
}
}
}
}
public class WinTest{
public static void main(String[] args) {
WindowRun windowRun = new WindowRun();
Thread thread1 = new Thread(windowRun);
Thread thread2 = new Thread(windowRun);
Thread thread3 = new Thread(windowRun);
thread1.setName("窗口一");
thread2.setName("窗口二");
thread3.setName("窗口三");
thread1.start();
thread2.start();
thread3.start();
}
}
开发优先选择实现runnable接口,继承只能继承一个,实现多个
解决线程安全问题
package com.atjava.test;
class WindowRun implements Runnable{
private int ticket = 100;
private Object obj = new Object();
@Override
public void run() {
while (true){
synchronized (obj){
if(ticket > 0){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖票,票号为:" + ticket);
ticket--;
}else {
break;
}
}
}
}
}
public class WinTest{
public static void main(String[] args) {
WindowRun windowRun = new WindowRun();
Thread thread1 = new Thread(windowRun);
Thread thread2 = new Thread(windowRun);
Thread thread3 = new Thread(windowRun);
thread1.setName("窗口一");
thread2.setName("窗口二");
thread3.setName("窗口三");
thread1.start();
thread2.start();
thread3.start();
}
}
obj作为锁,锁的要求是多个线程共用一把锁,new了一次window,new 了一次Object
二、使用同步方法解决线程安全问题 synchronized void sale(),省去了写同步监视器,如果普通方法锁默认为this.
如果静态方法锁为当前类
浙公网安备 33010602011771号