分别继承Thread和实现Runnable,创建三个线程卖票。
package com.itheima;
class MyThread extends Thread{
private static int tickets = 100;
@Override
public void run() {
while (true){
if(tickets > 0){
System.out.println(Thread.currentThread().getName() + ": 卖票,票号为:" + tickets );
tickets--;
}else return;
}
}
}
public class T {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
thread1.setName("窗口1");
thread1.start();
MyThread thread2 = new MyThread();
thread2.setName("窗口2");
thread2.start();
MyThread thread3 = new MyThread();
thread3.setName("窗口3");
thread3.start();
}
}
==========================================================
package com.itheima;
class MyThread implements Runnable{
private int tickets = 100;
@Override
public void run() {
while (true){
if(tickets > 0){
System.out.println(Thread.currentThread().getName() + ": 卖票,票号为:" + tickets );
tickets--;
}else return;
}
}
}
public class T {
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread);
thread1.setName("窗口1");
thread1.start();
Thread thread2 = new Thread(myThread);
thread2.setName("窗口2");
thread2.start();
Thread thread3 = new Thread(myThread);
thread3.setName("窗口3");
thread3.start();
}
}
=================================================
仔细会发现有重票问题。多个线程操作共享数据。
问题: 出现重票、错票 -->出现了线程的安全问题。
原因: 当某个线程操作车票的过程中,尚未操作完成时,其他线程参与进来,也操作车票。
解决: 当一个线程a在操作ticket的时候,其他线程不能参与进来。直到线程a操作完ticket时,其他线程才可以操作ticket。即使线程a出现了阻塞,也不能被改变。
package com.itheima;
class MyThread implements Runnable{
private int tickets = 100;
@Override
public void run() {
while (true){
init();
if(tickets == 0){
break;
}
}
}
private synchronized void init(){
if(tickets > 0){
System.out.println(Thread.currentThread().getName() + ": 卖票,票号为:" + tickets );
tickets--;
}
}
}
public class T {
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread);
thread1.setName("窗口1");
thread1.start();
Thread thread2 = new Thread(myThread);
thread2.setName("窗口2");
thread2.start();
Thread thread3 = new Thread(myThread);
thread3.setName("窗口3");
thread3.start();
}
}