Single Thread Execution

本文介绍了一个使用Java实现的简单示例,通过synchronized关键字确保了多个线程在访问共享资源时的线程安全性。示例中定义了一个Gate类来模拟门禁系统,该系统记录通过的人名及其地址,并检查两者首字母是否一致。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Gate
{
    private int counter = 0;
    private String name="nobody";
    private String address = "nowhere";
    public synchronized void pass(String name,String address)
    {
        this.counter++;
        this.name = name;
        this.address = address;
        check();
    }
    public synchronized String toString()
    {
        return "No."+counter+":"+name+","+address;
    }
    private void check()
    {
        if(name.charAt(0)!=address.charAt(0))
        {
            System.out.println("BROKEN"+this.toString());
            System.out.println("name[0]"+name.charAt(0));
            System.out.println("address[0]"+address.charAt(0));
        }else
        {
            System.out.println("yes");
        }
    }
}
class UserThread extends Thread
{
    private final Gate gate;
    private final String myName;
    private final String myAddress;
    
    public UserThread(Gate gate,String myName,String myAddress)
    {
        this.gate = gate;
        this.myAddress = myAddress;
        this.myName = myName;
    }
    public void run()
    {
        System.out.println(myName+"BEGIN");
        while(true)
        {
            
            gate.pass(myName, myAddress);
        }
    }
}

public class Test {

    public synchronized static void main(String[] args) throws UnsupportedEncodingException, IOException, InterruptedException {
        
        Gate gate = new Gate();
        new UserThread(gate,"Alice","Alaska").start();
        new UserThread(gate,"Bobby","Brazil").start();
        new UserThread(gate,"Chris","Canda").start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值