多线程之线程安全问题
使用同步代码块方式
class WindowsSynchronized extends Thread {
private static int ticket = 100;
@Override
public void run() {
while (true) {
synchronized (WindowsSynchronized.class) {
if (ticket > 0) {
System.out.println(getName() + ":卖票,票号为: " + ticket);
ticket--;
} else {
break;
}
}
}
}
}
public class ThreadTestSynchronized {
public static void main(String[] args) {
WindowsSynchronized windows1 = new WindowsSynchronized();
WindowsSynchronized windows2 = new WindowsSynchronized();
WindowsSynchronized windows3 = new WindowsSynchronized();
windows1.setName("A1:");
windows2.setName("A2:");
windows3.setName("A3:");
windows1.start();
windows2.start();
windows3.start();
}
}
*使用同步方法方式
class WindowsSynchronizedFuncion extends Thread {
private static int ticket = 100;
@Override
public void run() {
while (true) {
show();
}
}
public static synchronized void show() {
synchronized (WindowsSynchronized.class) {
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + ":卖票,票号为: " + ticket);
ticket--;
}
}
}
}
public class ThreadSynchronizedFunction {
public static void main(String[] args) {
Thread thread1 = new WindowsSynchronizedFuncion();
Thread thread2 = new WindowsSynchronizedFuncion();
Thread thread3 = new WindowsSynchronizedFuncion();
thread1.setName("窗口1:");
thread2.setName("窗口2:");
thread3.setName("窗口3:");
thread1.run();
thread2.run();
thread3.run();
}
}
*使用lock 锁方式
class Account {
private double balance;
private ReentrantLock lock = new ReentrantLock();
public Account(double balance) {
this.balance = balance;
}
public void deposit(double amt) {
lock.lock();
try {
if (amt > 0) {
balance += amt;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":存钱成功。余额为:" + balance);
}
} finally {
lock.unlock();
}
}
}
class Customer implements Runnable {
Account account = new Account(0);
@Override
public void run() {
for (int i = 0; i < 3; i++) {
account.deposit(1000);
}
}
}
public class AccountTest {
public static void main(String[] args) {
Customer customer = new Customer();
Thread thread1 = new Thread(customer);
Thread thread2 = new Thread(customer);
thread1.setName("甲");
thread2.setName("乙");
thread1.start();
thread2.start();
}
}