スレッドを継承し、Runnableをそれぞれ実装し、チケットを販売するための3つのスレッドを作成します。
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がチケットを操作している場合、他のスレッドは参加できません。スレッドがチケットの操作を終了するまで、他のスレッドがチケットを操作できます。スレッド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();
}
}