Another BlockingQueue [ October 26th, 2008 ] Posted in » Study

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.myhue.www;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author Hity
 */
public class Sender implements Runnable {

    Random random = new Random();
    BlockingQueue<Character> bQueue = new ArrayBlockingQueue<Character>(2);

    public BlockingQueue getBlockingQueue() {
        return bQueue;
    }

    public void run() {
        try {
            for (char c = ‘a’; c <= ‘z’; c++) {
                bQueue.put(new Character(c));
                TimeUnit.MILLISECONDS.sleep(random.nextInt(500));
            }
        } catch (InterruptedException e) {
            System.out.println(”sender sleep Interrupted”);
        }
    }

    public static void main(String[] args) throws Exception {
        Sender s = new Sender();
        Reader r = new Reader(s);
        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(s);
        exec.execute(r);
        TimeUnit.SECONDS.sleep(8);
        exec.shutdownNow();
    }
}

class Reader implements Runnable {
    Random random = new Random();
    BlockingQueue bQueue;
    Reader(Sender sender) throws IOException {
        bQueue = sender.getBlockingQueue();
    }
    public void run() {
        try {
            while (!Thread.interrupted()) {
                System.out.println(bQueue.take());
            }
        } catch (InterruptedException ex) {
            System.out.println(”Reader sleep Interrupted”);
        }
    }
}

BlockingQueue

本程序是thinking in java 4th的课后练习题,通过Java SE5的BlockingQueue来解决生产者与消费者的问题。通过BlockingQueue可以实现解耦。每个类都有自己的BlockingQueue通信。

package concurrency;

//: concurrency/ToastOMatic.java
// A toaster that uses queues.
import java.util.concurrent.*;
import java.util.*;
import static net.mindview.util.Print.*;

class Toast {

    public enum Status {

        DRY, BUTTERED, JAMMED, JELLY
    }
    private Status status = Status.DRY;
    private final int id;

    public Toast(int idn) {
        id = idn;
    }

    public void butter() {
        status = Status.BUTTERED;
    }

    public void jam() {
        status = Status.JAMMED;
    }
    public void jelly() {
        status = Status.JELLY;
    }
    public Status getStatus() {
        return status;
    }

    public int getId() {
        return id;
    }

    public String toString() {
        return “Toast ” + id + “: ” + status;
    }
}

class ToastQueue extends LinkedBlockingQueue<Toast> {
}

class Toaster implements Runnable {

    private ToastQueue toastQueue;
    private int count = 0;
    private Random rand = new Random(47);

    public Toaster(ToastQueue tq) {
        toastQueue = tq;
    }

    public void run() {
        try {
            while (!Thread.interrupted()) {
                TimeUnit.MILLISECONDS.sleep(
                        100 + rand.nextInt(500));
                // Make toast
                Toast t = new Toast(count++);
                print(t);
                // Insert into queue
                toastQueue.put(t);
            }
        } catch (InterruptedException e) {
            print(”Toaster interrupted”);
        }
        print(”Toaster off”);
    }
}

// Apply butter to toast:
class Butterer implements Runnable {

    private ToastQueue dryQueue,  butteredQueue;

    public Butterer(ToastQueue dry, ToastQueue buttered) {
        dryQueue = dry;
        butteredQueue = buttered;
    }

    public void run() {
        try {
            while (!Thread.interrupted()) {
                // Blocks until next piece of toast is available:
                Toast t = dryQueue.take();
                t.butter();
                print(t);
                butteredQueue.put(t);
            }
        } catch (InterruptedException e) {
            print(”Butterer interrupted”);
        }
        print(”Butterer off”);
    }
}

// Apply jam to buttered toast:
class Jammer implements Runnable {

    private ToastQueue butteredQueue,  finishedQueue;

    public Jammer(ToastQueue buttered, ToastQueue finished) {
        butteredQueue = buttered;
        finishedQueue = finished;
    }

    public void run() {
        try {
            while (!Thread.interrupted()) {
                // Blocks until next piece of toast is available:
                Toast t = butteredQueue.take();
                t.jam();
                print(t);
                finishedQueue.put(t);
            }
        } catch (InterruptedException e) {
            print(”Jammer interrupted”);
        }
        print(”Jammer off”);
    }
}
//向土司里面加果冻
class Jelly implements Runnable {

    private ToastQueue finishedQueue,  jammerQueue;

    Jelly(ToastQueue finishedQueue, ToastQueue jammerQueue) {
        this.finishedQueue = finishedQueue;
        this.jammerQueue = jammerQueue;
    }

    public void run() {
        try {
            while (!Thread.interrupted()) {
                Toast jam = jammerQueue.take();
                jam.jelly();
                print(jam);
                finishedQueue.add(jam);
            }
        } catch (InterruptedException ex) {
            print(”Jelly off!”);
        }
    }
}
//制作混合土司
class MixToast {

    ExecutorService exec = Executors.newCachedThreadPool();
    ToastQueue dryQueue = new ToastQueue(),
            butteredQueue = new ToastQueue(),
            jammerQueue = new ToastQueue();

    public ToastQueue makeMixToast() {
        exec.execute(new Toaster(dryQueue));
        exec.execute(new Butterer(dryQueue, butteredQueue));
        exec.execute(new Jammer(butteredQueue, jammerQueue));
        return jammerQueue;
    }

    public void shutDownNow() {
        exec.shutdownNow();
    }
}
// Consume the toast:
class Eater implements Runnable {

    private ToastQueue finishedQueue;
    private int counter = 0;

    public Eater(ToastQueue finished) {
        finishedQueue = finished;
    }

    public void run() {
        try {
            while (!Thread.interrupted()) {
                // Blocks until next piece of toast is available:
                Toast t = finishedQueue.take();
                // Verify that the toast is coming in order,
                // and that all pieces are getting jammed:
                if (t.getId() != counter++ ||
                        t.getStatus() != Toast.Status.JELLY) {
                    print(”>>>> Error: ” + t);
                    System.exit(1);
                } else {
                    print(”Chomp! ” + t);
                }
            }
        } catch (InterruptedException e) {
            print(”Eater interrupted”);
        }
        print(”Eater off”);
    }
}

public class ToastOMatic {

    public static void main(String[] args) throws Exception {
        ToastQueue jammerQueue;
        ToastQueue finishedQueue = new ToastQueue();
        ExecutorService exec = Executors.newCachedThreadPool();
        MixToast m=new MixToast();
        jammerQueue = m.makeMixToast();
        exec.execute(new Jelly(finishedQueue, jammerQueue));
        exec.execute(new Eater(finishedQueue));
        TimeUnit.SECONDS.sleep(5);
        m.shutDownNow();
        exec.shutdownNow();
    }
} /* (Execute to see output) *///:~

October 21st, 2008 | Leave a Comment

Producer and Consumer

package net.myhue.test;

import java.util.concurrent.*;

public class Restaurant {
 ExecutorService execs = Executors.newCachedThreadPool();
 public Beff beff;
 Producer producer = new Producer(this);
 Consumer consumer = new Consumer(this);

 public Restaurant() {
  execs.execute(producer);
  execs.execute(consumer);
 }
 public static void main(String[] args){
  new Restaurant();
 }
}

// 牛肉
class Beff {
 private final int orderNum;

 Beff(int orderNum) {
  this.orderNum = orderNum;
 }

 @Override
 public String toString() {
  return “Beff ” + orderNum;
 }
}

// 生产者
class Producer implements Runnable {
 Restaurant restaurant;
 private int count=0;
 Producer(Restaurant restaurant) {
  this.restaurant = restaurant;
 }

 @Override
 public void run() {
  // TODO Auto-generated method stub
  try {
   while (!Thread.interrupted()) {
    synchronized (this) {
     while (restaurant.beff != null){
      System.out.println(”Can’t Producut,Consumer is eating”);
      wait();
     }      
    }
    if(count++==100){
     System.out.println(”Beff Max Producted!”);
     restaurant.execs.shutdownNow();
    }
    synchronized (restaurant.consumer){
     System.out.println(”Produce beff!”);
     restaurant.beff = new Beff(count);
     restaurant.consumer.notifyAll();
    }
   }
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   System.out.println(”Producer interrupted!!!”);
  }
 }

}

// 消费者
class Consumer implements Runnable {
 Restaurant restaurant;

 Consumer(Restaurant restaurant) {
  this.restaurant = restaurant;
 }

 @Override
 public void run() {
  // TODO Auto-generated method stub
  try{
   while(!Thread.interrupted()){
    synchronized (this) {
     while(restaurant.beff==null){
      System.out.println(”Beff isn’t get ready,peasure wait!”);
      wait();
     }
    }
    synchronized (restaurant.producer){
     eat();
     restaurant.producer.notifyAll();
    }
   }
  }catch(InterruptedException e){
   System.out.println(”Consumer interrupted!!”);
  }
 }
 private void eat(){
  System.out.println(”eating beff!”);
  restaurant.beff=null;
 }
}

October 14th, 2008 | Leave a Comment

Join and interrupt

package net.myhue.test;

import java.util.concurrent.TimeUnit;

public class JoinRunnable implements Runnable{
 Thread t;
 String name;
 public JoinRunnable(Thread t,String name){
  this.t=t;
  this.name=name;
 }
 @Override
 public void run() {
  // TODO Auto-generated method stub
  System.out.println(”will be join!”);
  try {
   t.join();//只有当t运行完以后,当前进程才继续运行。
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   System.out.println(”Exception!!!”);
  }
  System.out.println(name+this);
 }
 
}
class MyTest implements Runnable{
 Thread t;
 MyTest(){
  t=new Thread(this);
  //t.setDaemon(true);//设置后台进程后,主程序运行完毕后台程序将被忽略
  t.start();
 }
 public static void main(String[] args){
  JoinRunnable j=new JoinRunnable(new MyTest().t,”Join”);
  Thread t1 = new Thread(j);  
  t1.start();
  t1.interrupt();//终止对join的调用
 }

 @Override
 public void run() {
  // TODO Auto-generated method stub
  try {
   TimeUnit.MILLISECONDS.sleep(1500);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   System.out.println(”Miss sleep!”);
  }
  System.out.println(”TEST”);
 }
}

September 21st, 2008 | Leave a Comment

UncaughtExceptionHandler

线程之间相互独立,在main里面是无法捕获子线程的异常的。java se5提供了UncaughtExceptionHandler,用来捕获接近死亡的线程。具体用法如下所示

package net.myhue.test;

import java.util.concurrent.*;

public class CaptureUncaughtException {

 public static void main(String[] args) {
  ExecutorService exec = Executors
    .newCachedThreadPool(new MyThreadFactory());
  exec.execute(new UncaughtException1());  
 }
}

class UncaughtException1 implements Runnable {

 @Override
 public void run() {
  // TODO Auto-generated method stub
  System.out.println(”——–”);
  throw new RuntimeException(”Thread test!”);
 }
}

class MyUncaughtException implements Thread.UncaughtExceptionHandler {
 @Override
 public void uncaughtException(Thread t, Throwable e) {
  // TODO Auto-generated method stub
  System.out.println(t + ” ” + e);
 }

}

class MyThreadFactory implements ThreadFactory {

 @Override
 public Thread newThread(Runnable r) {
  // TODO Auto-generated method stub
  Thread t = new Thread(r);
  t.setDaemon(true);
  t.setUncaughtExceptionHandler(new MyUncaughtException());
  return t;
 }

}

September 21st, 2008 | Leave a Comment

斐波纳契数

斐波那契数列的排列是:1,1,2,3,5,8,13,21,34,55,89,144,。。。。。。
依次类推下去,你会发现,它后一个数等于前面两个数的和。在这个数列中的数字,就被称为斐波那契数。2是第3个斐波那契数。

这个级数与大自然植物的关系极为密切。几乎所有花朵的花瓣数都来自这个级数中的一项数字:菠萝表皮方块形鳞苞形成两组旋向相反的螺线,它们的条数必须是这个级数中紧邻的两个数字(如左旋8行,右旋13行);还有向日葵花盘……倘若两组螺线条数完全相同,岂不更加严格对称?可大自然偏不!直到最近的1993年,人们才对这个古老而重要的级数给出真正满意的解释:此级数中任何相邻的两个数,次第相除,其比率都最为接近0.618034……这个值,它的极限就是所谓的”黄金分割数”。

它有一个递推关系,
f(1)=1   
f(2)=1   
f(n)=f(n-1)+f(n-2),其中n>=2

以下为java底递归方式:并在多线程下做了测试:

package net.myhue.test;

public class FibonacciSeries implements Runnable {
 long coefficient;
 public long fibonacciSeries;
 public long loop;
 FibonacciSeries(long coefficient) {
  this.coefficient = coefficient;
 }

 @Override
 public void run() {
  // TODO Auto-generated method stub
  fibonacciSeries = getFibonacciSeries(coefficient);
  
 }

 public long getFibonacciSeries(long num) {
  loop++;
  if (num <= 0)
   return 1;
  return getFibonacciSeries(num - 1) + getFibonacciSeries(num - 2);
 }

 public static void main(String[] args) {
  FibonacciSeries f1 = new FibonacciSeries(20);
  FibonacciSeries f2 = new FibonacciSeries(21);
  Thread thread1 = new Thread(f1);
  Thread thread2 = new Thread(f2);
  long time=System.nanoTime();
  thread1.start();
  thread2.start();
  while (true) {
   if (!thread1.isAlive() && !thread2.isAlive()) {
    System.out.println((double) f2.fibonacciSeries
      /f1.fibonacciSeries);
    break;
   }

  }
  System.out.println(System.nanoTime()-time);
  time=System.nanoTime();
  f1.run();
  f2.run();
  System.out.println((double) f2.fibonacciSeries
    /f1.fibonacciSeries);
  System.out.println(System.nanoTime()-time);
  long i=1;
  long j=1;
  int loop = 21;
  time=System.nanoTime();
  while(loop–>0){
   j=i+j;
   i=j-i;
  }
  System.out.println((double)j/i);
  System.out.println(System.nanoTime()-time);
 }
}/*Output:

1.6180339901755971
34638201
1.6180339901755971
1683175
1956
1.6180339901755971
*///:~

由输入结果可以看出递归算法效率极差,原因是因为递归调用的时候是以类似二叉树的形式调用的,其叶子节点值为一,然后将每一个叶子节点值累计相加.而普通算法则不是这样.

September 15th, 2008 | 4 Comments

java SE5中的线程执行器

java SE5对并行开发进行了扩展,在此之前.运行一个线程必须先建立一个Thread对象,然后调用这个对象的start方法,java se5以后Executors是执行线程的首选方式,其类似于命令模式.Thread.yield();表示此线程已经完成最重要的部分,可以进行切换了.

import java.util.concurrent.Executors;

public class SaySomething implements Runnable {
 public static int temp;
 public final int ID=temp++;
 public void run() {
  for (int i = 0; i < 3; i++) {
   System.out.println(”Hello SaySomething!! ” + i+”Thread id=”+ID);
   Thread.yield();
  }
 }
}

class Test {
 public static void main(String[] args) {
  java.util.concurrent.ExecutorService ex = Executors
    .newCachedThreadPool();
  for (int i = 0; i < 3; i++)
   ex.execute(new SaySomething());
 }
}

September 14th, 2008 | Leave a Comment

java闭包的练习

class Testclosures{
static { => int } answer = { => 42 };
public static void main(String[] args) {
int i = answer.invoke();
System.out.println(i);
int temp=new Testclosures().add({int x,int y=>x*x+y*y});
System.out.println(temp);
}
public int add({ int,int=>int } s){
return s.invoke(3, 4);
}

}

August 16th, 2008 | 1 Comment

java7中的闭包

以前只听说java7要增加闭包,一直没弄明白,看了IBM社区的一篇Java 理论与实践: 闭包之争》对闭包又了一定的了解。直到看了Zdeněk Troníček博客上的一篇文章才豁然开朗:闭包是可以包含自由(未绑定)变量的代码块;这些变量不是在这个代码块或者任何全局上下文中定义的,而是在定义代码块的环境中定义。
一下出至Zdeněk Troníček的blog:

Function types are used when we want to refer to closures. We can declare a variable of function type and assign to it a reference to a closure. A function type is written as follows: { formal parameters => return type }. Formal parameters are optional. The return type can be any type or void. For example, { int, String => void } means a function with two arguments (int and String) and return type void. Any function with a compatible list of argument types and compatible return type can be assigned to a variable of function type.

public class DeepThought {

// { => int } means a function with no arguments and return type int
static { => int } answer = { => 42 };

public static void main(String[] args) {
int i = answer.invoke();
System.out.println(i);
}

}
A function with one int argument and return type String:

{ int => String } toBinary = { int x => Integer.toBinaryString(x) };
String binary11 = toBinary.invoke(11); // will return 1011
A function with no arguments and return type void:

{ => void } sayHello = { => System.out.println(”Hello”); };
sayHello.invoke(); // will print “Hello”
Function types can be used as types of arguments:

static void doTwice({ => void } block) {
block.invoke();
block.invoke();
}

public static void main(String[] args) {
doTwice({ => System.out.println(”deja vu”); });
}
They can also serve as a return type:

static { => boolean } makeCond() {
return { => Math.random() < 0.8 };
}

public static void main(String[] args) {
{ => boolean } cond = makeCond();
while (cond.invoke()) {
System.out.println(”trying…”);
}
}

——————————————————————————–

Exercises
Write a method that invokes an action on each value of array of ints. The action is passed in a function variable.
Write a method that returns a closure which checks if a value is from a given interval. Bounds of the interval are arguments of the method.
Write a method that selects values from a list in accordance with a predicate passed in a function variable.
Solutions
static void perform(int[] values, { int => void } action) {
for (int n: values) {
action.invoke(n);
}
}

public static void main(String[] args) {
int[] v = { 2, 3, 5, 7, 11 };
perform(v, { int x => System.out.println(x); });
}
static { int => boolean } makeInterval(int a, int b) {
return { int x => a <= x && x <= b };
}

public static void main(String[] args) {
{ int => boolean } interval = makeInterval(10, 20);
System.out.println(interval.invoke(15));
}
static List select(List values, { T => boolean } cond) {
List selected = new ArrayList();
for (T t: values) {
if (cond.invoke(t)) { selected.add(t); }
}
return selected;
}

public static void main(String[] args) {
List cities =
Arrays.asList(”London”, “New York”, “Prague”, “San Francisco”);
List shortCities =
select(cities, { String s => s.length() <= 6 });
System.out.println(shortCities);
}

August 16th, 2008 | Leave a Comment

混乱的构造器重载

/**
* Java的重载解析过程是以两阶段运行的。
* 第一阶段选取所有可获得并且可应用的方法或构造器。
* 第二阶段在第一阶段选取的方法或构造器中选取最精确的一个。
* 如果一个方法或构造器可以接受传递给另一个方法或构造器的任何参数,
* 那么我们就说第一个方法比第二个方法缺乏精确性[JLS 15.12.2.5]。
* double[] dArray也是一个Object类型,所以double[] dArray比Object精确。
* @author Hity
*
*/

public class Confusing {
private Confusing(Object o) {
System.out.println(”Object”);
}
private Confusing(double[] dArray) {
System.out.println(”double array”);
}
public static void main(String[] args) {
new Confusing(null);
}
}

July 18th, 2008 | Leave a Comment

Powered by WordPress | Blue Weed by Blog Oh! Blog | Entries (RSS) and Comments (RSS).