import java.util.*;
public class ThreadLocal {
private Map storage =
Collections.synchronizedMap(new HashMap());
public Object get() {
Thread current = Thread.currentThread();
Object o = storage.get(current);
if(o == null && !storage.containsKey(current)) {
o = initialValue();
storage.put(current, o);
}
return o;
}
public void set(Object o) {
storage.put(Thread.currentThread(), o);
}
public Object initialValue() {
return null;
}
}
public class Resource {
private static final ThreadLocal threadLocal =
new ThreadLocal();
public static SomeResource getResource() {
SomeResource resource =
(SomeResource) threadLocal.get();
if(resource == null) {
resource = new SomeResource();
threadLocal.set(resource);
}
return resource;
}
}
import java.io.*;
import java.util.logging.*;
public class SimpleThreadLogger {
private static final ThreadLocal threadLocal =
new ThreadLocal();
public static void log(String msg) {
getThreadLogger().log(Level.INFO, msg);
}
private static Logger getThreadLogger() {
Logger logger = (Logger) threadLocal.get();
if(logger == null) {
try {
logger = Logger.getLogger(
Thread.currentThread().getName());
// Logger 預設是在L台?br> // 我們加入一個檔案出的Handler
// 它會輸出XML的記錄文?br> logger.addHandler(
new FileHandler(
Thread.currentThread().getName()
+ ".log"));
}
catch(IOException e) {}
threadLocal.set(logger);
}
return logger;
}
}
public class LoggerTest {
public static void main(String[] args) {
new TestThread("thread1").start();
new TestThread("thread2").start();
new TestThread("thread3").start();
}
}
class TestThread extends Thread {
public TestThread(String name) {
super(name);
}
public void run() {
for(int i = 0; i < 10; i++) {
SimpleThreadLogger.log(getName() +
": message " + i);
try {
Thread.sleep(1000);
}
catch(Exception e) {
SimpleThreadLogger.log(e.toString());
}
}
}
}
import java.util.LinkedList;
public class ProductTable {
private LinkedList products = new LinkedList();
public synchronized void addProduct(Product product) {
while(products.size() >= 2) { // 定w限制?2
try {
wait();
}
catch(InterruptedException e) {}
}
products.addLast(product);
notifyAll();
}
public synchronized Product getProduct() {
while(products.size() <= 0) {
try {
wait();
}
catch(InterruptedException e) {}
}
Product product = (Product) products.removeFirst();
notifyAll();
return product;
}
}
public class Producer extends Thread {
private ProductTable productTable;
public Producer(ProductTable productTable) {
this.productTable = productTable;
}
public void run() {
System.out.println("Produce integer......");
for(int product = 1; product <= 10; product++) {
try {
// wait for a random time
Thread.sleep((int) Math.random() * 3000);
}
catch(InterruptedException e) {
e.printStackTrace();
}
productTable.setIntProduct(product);
}
}
}
public class Consumer extends Thread {
private ProductTable productTable;
public Consumer(ProductTable productTable) {
this.productTable = productTable;
}
public void run() {
for(int i = 1; i <= 10; i++) {
try {
// wait for a random time
Thread.sleep((int) (Math.random() * 3000));
}
catch(InterruptedException e) {
e.printStackTrace();
}
productTable.getProductInt();
}
}
}
生產者將產品放至桌上Q而消費者將產品從桌上取赎ͼ所以桌子是個維h否讓被放|或消耗產品的地方Q由它來決定誰必須等待與通知Q?
public class ProductTable {
private int productInt = -1; // -1 for no product
public synchronized void setIntProduct(int product) {
if(productInt != -1) {
try {
wait();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
productInt = product;
System.out.println("set (" + product + ")");
notify();
}
public synchronized int getProductInt() {
if(productInt == -1) {
try {
wait();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
int p = productInt;
System.out.println("Get (" + productInt + ")");
productInt = -1;
notify();
return p;
}
}
import java.util.LinkedList;
public class Channel {
private LinkedList requests;
private WorkerThread[] workerThreads;
public Channel(int threadNumber) {
requests = new LinkedList();
workerThreads = new WorkerThread[threadNumber];
for(int i = 0; i < workerThreads.size(); i++) {
workerThreads[i] = new WorkerThread();
workerThreads[i].start();
}
}
public synchronized void putRequest(Request request) {
while(requests.size() >= 2) { // 定w限制?2
try {
wait();
}
catch(InterruptedException e) {}
}
requests.addLast(request);
notifyAll();
}
public synchronized Request getProduct() {
while(requests.size() <= 0) {
try {
wait();
}
catch(InterruptedException e) {}
}
Request request = (Request) requests.removeFirst();
notifyAll();
return request;
}
}
public class Request() {
// ....
public void execute() {
// do some work....
}
}
public class WorkerThread extends Thread {
// ...
public void run() {
while(true) {
Request request = channel.getRequest();
request.execute();
}
}
}
public class RequestQueue {
private java.util.LinkedList queue;
public RequestQueue() {
queue = new java.util.LinkedList();
}
public synchronized Request getRequest() {
while(queue.size() <= 0) {
try {
wait();
}
catch(InterruptedException e) {}
}
return (Request) queue.removeFirst();
}
public synchronized void putRequest(Request request) {
queue.addLast(request);
notifyAll();
}
}