JAVA多线程设计模式一 Single Threaded Execution

本文深入探讨了在Gate类中实现的并发控制和线程安全机制,通过多线程实例展示了如何使用synchronized关键字确保资源的正确访问和状态一致性。重点介绍了Gate类的方法如何在不同线程间协调资源访问,避免了数据竞争和死锁问题。
public 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;
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
		}
		this.address = address;
		check();
	}

	public  String toString() {
		return "No." + counter + ": " + name + ", " + address;
	}

	private void check() {
		if (name.charAt(0) != address.charAt(0)) {
			System.out.println("***** BROKEN ***** " + toString());
		}
	}
}

 

 

 

 

public 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.myname = myname;
		this.myaddress = myaddress;
	}

	public void run() {
		System.out.println(myname + " BEGIN");
		while (true) {
			gate.pass(myname, myaddress);
		}
	}
}

 

 

 

public class Main {
    public static void main(String[] args) {
        System.out.println("Testing Gate, hit CTRL+C to exit.");
        Gate gate = new Gate();
        new UserThread(gate, "Alice", "Alaska").start();
        new UserThread(gate, "Bobby", "Brazil").start();
        new UserThread(gate, "Chris", "Canada").start();
    }
}

 

Gate 类中的方法,同步关键字的有无。 执行程序看看。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值