Single Threaded Execution

定义

Single Threaded Execution模式定义:同一时间能够执行的线程只有一个。

引例

一次只允许一个人通过的门 

类说明
名字说明
Main创建门,让3个人不断通过
Gate门,通过时记录姓名和出生地。如果姓名和出生地不一致,拒绝通过
UserThread人,人们不断通过门
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();
	}
}
public class Gate {
	private int counter = 0;
	private String name = "Nobody";
	private String address = "Nowhere";

	/* pass方法加synchronized修饰 */
	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 ***** " + 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);
		}
	}
}

小知识:final修饰的字段不允许重复赋值,final修饰的类不能有子类。

结果: 

Testing Gate, hit CTRL+C to exit.
Alice BEGIN
Chris BEGIN
Bobby BEGIN

 有点多线程基础的人觉得这是很简单,就是使用了synchronized关键字,保证逻辑的正确。

角色

Single Threaded Execution模式出现了一个发挥SharedResource(共享资源)的类,刚才的例子中Gate就是这种类。在SharedResource类中方法分为2类,线程安全的方法和线程不安全的方法,对于线程不安全的方法要加synchronized进行保护。只允许单线程执行的程序范围叫做临界区。

何时使用

多线程、多个线程访问、状态可能发生变化、确保安全性时

生存性与死锁

举个例子,Alice与Bobby要吃意大利面,桌上只有一把勺子和叉子,要想吃到面两者缺一不可,这时A拿了叉子B拿了勺子,两者都在等对方放下手中的餐具,于是陷入了等待。产生了死锁。

在Single Threaded Execution模式中满足一下条件就有可能发生死锁。

1.有多个sharedResource角色

2.线程在持有某个shareResource角色时,还想获得其他shareResource角色。

3.获取shareResource角色的锁的顺序时不固定的

对synchronized思考

使用synchronized一定要明白以下几点

1.synchronized到底保护什么?

2.synchronized以什么单位保护?

3.使用那个锁保护?

扩展性思考

除了使用synchronized关键字保护临界区的代码,我们还可以使用semaphore,控制资源的释放和回收。

深入思考

我们看这么一个死锁问题,勺子和叉子吃面问题。同时获得右手勺子和左手叉子才能吃面。

public class Tool {
	private final String name;

	public Tool(String name) {
		this.name = name;
	}

	public String toString() {
		return "[ " + name + " ]";
	}
}
/**
 * 模拟吃面,需要左手叉右手刀
 *
 **/
public class EaterThread extends Thread {
	private String name;
	private final Tool lefthand;
	private final Tool righthand;

	public EaterThread(String name, Tool lefthand, Tool righthand) {
		this.name = name;
		this.lefthand = lefthand;
		this.righthand = righthand;
	}

	public void run() {
		while (true) {
			eat();
		}
	}

	/*
	 * 1.演示synchronized关键字对象锁,对多个不同对象加锁,注意死锁的产生 
	 * 2.锁一定要小,不然效率不高 
	 * 3.临界区要小
	 */
	public void eat() {
		synchronized (lefthand) {
			System.out.println(name + " takes up " + lefthand + " (left).");
			synchronized (righthand) {
				System.out.println(name + " takes up " + righthand + " (right).");
				System.out.println(name + " is eating now, yam yam!");
				System.out.println(name + " puts down " + righthand + " (right).");
			}
			System.out.println(name + " puts down " + lefthand + " (left).");
		}
	}
}
public class Main {
	public static void main(String[] args) {
		System.out.println("Testing EaterThread, hit CTRL+C to exit.");
		Tool spoon = new Tool("Spoon");
		Tool fork = new Tool("Fork");
		// 改成两人获得餐具的顺序一致
		// new EaterThread("Alice", spoon,fork).start();
		new EaterThread("Alice", fork, spoon).start();
		new EaterThread("Bobby", spoon, fork).start();
	}
}

 

分析这个代码,会发生死锁吗?

Testing EaterThread, hit CTRL+C to exit.
Alice takes up [ Fork ] (left).
Bobby takes up [ Spoon ] (left).
 

答案:是。

修改的方法:1.两人获得餐具的顺序一致。注释中写的一样。2.让两个餐具同时出现。

public class Pair {
	private final Tool lefthand;
	private final Tool righthand;

	public Pair(Tool lefthand, Tool righthand) {
		this.lefthand = lefthand;
		this.righthand = righthand;
	}

	public String toString() {
		return "[ " + lefthand + " and " + righthand + " ]";
	}
}
public class Main {
	public static void main(String[] args) {
		System.out.println("Testing EaterThread, hit CTRL+C to exit.");
		Tool spoon = new Tool("Spoon");
		Tool fork = new Tool("Fork");
		Pair pair = new Pair(spoon, fork);
		new EaterThread("Alice", pair).start();
		new EaterThread("Bobby", pair).start();
	}
}

 这样就不会出现死锁了。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值