关于线程安全的演示代码
public class MyRunnable implements Runnable{
int i = 100;
@Override
public void run() {
while (true){
if (i<1){
System.out.println("票卖完了");
break;
}
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":正在出售第"+i+"张票");
--i;
}
}
}
public class ThreadTest {
public static void main(String[] args) {
MyRunnable my = new MyRunnable();
Thread thread1 = new Thread(my, "窗口1");
Thread thread2 = new Thread(my, "窗口2");
Thread thread3 = new Thread(my, "窗口3");
Thread thread4 = new Thread(my, "窗口4");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
出现卖重复票,漏票,负数票问题。
使用synchronized关键字解决问题
public class MyRunnable implements Runnable{
int i = 100;
@Override
public void run() {
while (true){
//票卖完结束
if (sellTickets())break;
}
}
//同步方法
public synchronized boolean sellTickets(){
if (i<1){
System.out.println("票卖完了");
return true;
}
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":正在出售第"+i+"张票");
--i;
return false;
}
}
使用Lock锁
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyRunnable implements Runnable{
int i = 100;
Lock lock = new ReentrantLock();
@Override
public void run() {
while (true){
lock.lock();
//票卖完结束
if (i<1){
System.out.println("票卖完了");
break;
}
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":正在出售第"+i+"张票");
--i;
try{
}finally {
lock.unlock();
}
}
}