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

被折叠的 条评论
为什么被折叠?



