- /**
- The following information are printed , and the Main thread blocked .
- Initialize Printer
- Initialize ShortThread
- 12ABCDEFGHIJKLMNOPQRSTUVWXYZ34
- */
- public class ShortThread {
- private Printer p = new Printer() ;
- public ShortThread(){
- System.out.println("Initialize ShortThread");
- new NumberThread().start() ;
- try {
- Thread.sleep(1000) ;
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- new AlphaThread().start() ;
- }
- class Printer{
- public Printer(){ System.out.println("Initialize Printer");}
- public void out(int x){ System.out.print(x) ; }
- public void out(char x){ System.out.print(x) ; }
- }
- class NumberThread extends Thread{
- public void run(){
- int index = 1 ;
- while(true){
- synchronized(p){
- p.out(index ++) ;
- p.out(index ++) ;
- if(index > 52) break ;
- try {
- p.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- class AlphaThread extends Thread{
- public void run(){
- byte index = 'A' ;
- while(true){
- synchronized(p){
- p.out((char)(index++)) ;
- p.notify() ;
- if ( index > 'Z') break ;
- }
- }
- }
- }
- public static void main(String[] args) {
- new ShortThread();
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/110320148961.html
来源: http://www.codesnippet.cn/detail/110320148961.html