多线程设计(1)---- 单一线程执行模式
单一线程执行模式
package com.thread.single.thread.execution.safe;
public class SafeUserThread extends Thread {
//final保证线程安全
private final String name;
private final String address;
private final SafeGate gate;
public SafeUserThread(String name, String address, SafeGate gate){
this.name = name;
this.address = address;
this.gate = gate;
}
@Override
public void run() {
System.out.println(name + " BEGIN");
while(true){
gate.pass(name,address);
}
}
}
package com.thread.single.thread.execution.safe;
public class SafeGate {
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();
}
private void check() {
if (this.name.charAt(0) != this.address.charAt(0)){
System.out.println("BROKEN ------> " + toString());
}
}
@Override
public synchronized String toString() {
return "Gate{" +
" name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
package com.thread.single.thread.execution.safe;
public class UserSafeMain {
public static void main(String[] args) {
SafeGate gate = new SafeGate();
new SafeUserThread("Alice","America",gate).start();
new SafeUserThread("Chris","China",gate).start();
}
}
使用的情况
- 多线程访问
- 状态开可能发生变化(共享变量)
- 需要保证线程安全时
复用时子类的UnsafeMethod也需要加synchronized
临界区大小直接决定性能
**
Semaphone
package com.thread.basic.semaphore;
import java.util.Random;
import java.util.concurrent.Semaphore;
public class SharedResourcesMain {
public static void main(String[] args) {
SharedResources sharedResources = new SharedResources(3);
for (int i = 0; i < 10 ; i++) {
new UserThread(sharedResources).start();
}
}
}
class Log {
public static void println(String s) {
System.out.println(Thread.currentThread().getName() + ": " + s);
}
}
class SharedResources{
private final Semaphore semaphore;
//资源限制
private final int permits;
private final static Random random = new Random(316159);
public SharedResources(int permits){
this.semaphore = new Semaphore(permits);
this.permits = permits;
}
public void useResources() throws InterruptedException {
//确定有可用资源直接返回
semaphore.acquire();
try {
doUse();
}finally {
//释放资源
semaphore.release();;
}
}
protected void doUse() throws InterruptedException {
Log.println("BEGIN: use = " + (permits - semaphore.availablePermits()));
Thread.sleep(random.nextInt(500));
Log.println("END: use = " + (permits - semaphore.availablePermits()));
}
}
class UserThread extends Thread{
private final static Random random = new Random(26535);
private final SharedResources sharedResources;
public UserThread(SharedResources sharedResources){
this.sharedResources = sharedResources;
}
@Override
public void run() {
try {
while (true){
sharedResources.useResources();
Thread.sleep(random.nextInt(3000));
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
}

浙公网安备 33010602011771号