[Java] [Multithreading] Venda de ingressos

Herdar Thread e implementar Runnable respectivamente e criar três threads para vender ingressos.

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();

    }
}


Insira a descrição da imagem aqui

====================================================== com
Insira a descrição da imagem aqui
cuidado Você vai descobrir que há votos pesados. Várias operações de thread compartilham dados.
Problema: Há votos pesados, votos errados -> problemas de segurança de thread aparecem.
Motivo: quando um thread está operando o ticket e a operação ainda não foi concluída, outros threads participam e também operam o ticket.
Solução: quando um thread a está operando o ticket, outros threads não podem participar. Até que o thread a termine de operar o tíquete, outros threads podem operar o tíquete. Mesmo se o thread a estiver bloqueado, ele não pode ser alterado.

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();

    }
}



Acho que você gosta

Origin blog.csdn.net/weixin_48180029/article/details/112978516
Recomendado
Clasificación