JAVA100例

来源:互联网 发布:seo外包安徽 编辑:程序博客网 时间:2024/05/16 02:01
[JAVA100例]001、Hello,Java    --------------------------------------------------------------------------------    public class HelloWorld {   public static void main(String[] args) {   System.out.println("Hello Java World!");   }   }  [JAVA100例]002、Java流程控制    --------------------------------------------------------------------------------    public class flowDemo{   public static void main(String[] arges){   int iPara1,iPara2,iEnd;   if(arges.length!=3)   {   System.out.println("USE :java flowDome parameter1 parameter2 circle");   System.out.println("parameter1 : 比较条件1,数字类型");   System.out.println("parameter2 : 比较条件2,数字类型");   System.out.println("circle :循环次数");   System.out.println("ego:java flowDome 1 2 5");   return;   }else{   iPara1 = Integer.parseInt(arges[0]);   iPara2 = Integer.parseInt(arges[1]);   iEnd = Integer.parseInt(arges[2]);   }   //if语句   if(iPara2>iPara1)   {   System.out.println("if 条件满足!");   System.out.println("第2个数比第1个数大!");   }   else   {   System.out.println("if 条件不满足!");   System.out.println("第2个数比第1个数小!");   }   //for循环操作   for(int i=0;i   {   System.out.println("这是for 第"+i+"次循环");   }   //while循环操作   int i=0;   while(i   {   System.out.println("这是while 第"+i+"次循环");   i++;   }   //do-while循环操作   int j=0;   do   {   System.out.println("这是do-while 第"+j+"次循环");   j++;   }while(j   }   }    [JAVA100例]003、数组数据操作    --------------------------------------------------------------------------------      public class myArray{   //初始化数组变量   char[] cNum = {´1´,´2´,´3´,´4´,´5´,´6´,´7´,´8´,´9´,´0´};   char[] cStr = {´a´,´b´,´c´,´d´,´e´,´f´,´g´,´h´,   ´i´,´j´,´k´,´l´,´m´,´n´,´o´,´p´,   ´q´,´r´,´s´,´t´,´u´,´v´,´w´,´x´,´y´,´z´};   int[] iMonth = {31,28,31,30,31,30,31,31,30,31,30,31};   String[] sMail = {"@","."};  /**   *方法说明:校验电子邮件   *输入参数:String sPara 被校验的电子邮件字符   *返回类型:boolean 如果校验的格式符合电子邮件格式返回true;否则返回false   */    public boolean isMail(String sPara){   for(int i=0;i   if(sPara.indexOf(sMail[i])==-1)   return false;    }   return true;   }  /**   *方法说明:判断是否是数字   *输入参数:String sPara。 需要判断的字符串   *返回类型:boolean。如果都是数字类型,返回true;否则返回false   */    public boolean isNumber(String sPara){   int iPLength = sPara.length();   for(int i=0;i   char cTemp = sPara.charAt(i);   boolean bTemp = false;   for(int j=0;j   if(cTemp==cNum[j]){   bTemp = true;   break;   }   }   if(!bTemp) return false;    }   return true;   }  /**   *方法说明:判断是否都是英文字符   *输入参数:String sPara。要检查的字符   *返回类型:boolean。如果都是字符返回true;反之为false   */    public boolean isString(String sPara){   int iPLength = sPara.length();   for(int i=0;i   char cTemp = sPara.charAt(i);   boolean bTemp = false;   for(int j=0;j   if(cTemp==cStr[j]){   bTemp = true;   break;   }   }   if(!bTemp) return false;    }   return true;   }  /**   *方法说明:判断是否是闰年   *输入参数:int iPara。要判断的年份   *返回类型:boolean。如果是闰年返回true,否则返回false   */    public boolean chickDay(int iPara){   return iPara%100==0&&iPara%4==0;   }  /**   *方法说明:检查日期格式是否正确   *输入参数:String sPara。要检查的日期字符   *返回类型:int。0 日期格式正确,-1 月或这日不合要求, -2 年月日格式不正确    */   public int chickData(String sPara){   boolean bTemp = false;   //所输入日期长度不正确   if(sPara.length()!=10) return -2;   //获取年   String sYear = sPara.substring(0,4);   //判断年是否为数字   if(!isNumber(sYear)) return -2;   //获取月份   String sMonth = sPara.substring(5,7);   //判断月份是否为数字   if(!isNumber(sMonth)) return -2;   //获取日   String sDay = sPara.substring(8,10);   //判断日是否为数字   if(!isNumber(sDay)) return -2;   //将年、月、日转换为数字   int iYear = Integer.parseInt(sYear);   int iMon = Integer.parseInt(sMonth);   int iDay = Integer.parseInt(sDay);   if(iMon>12) return -1;   //闰年二月处理   if(iMon==2&&chickDay(iYear)){   if(iDay>29) return 2;   }else{   if(iDay>iMonth[iMon-1]) return -1;   }   return 0;   }  /**   *方法说明:主方法,测试用   *输入参数:   *返回类型:   */    public static void main(String[] arges){   myArray mA = new myArray();   //校验邮件地址   boolean bMail = mA.isMail("tom@163.com");   System.out.println("1 bMail is "+bMail);   bMail = mA.isMail("tom@163com");   System.out.println("2 bMail is "+bMail);   //演示是否是数字   boolean bIsNum = mA.isNumber("1234");   System.out.println("1:bIsNum="+bIsNum);   bIsNum = mA.isNumber("123r4");   System.out.println("2:bIsNum="+bIsNum);   //演示是否是英文字符   boolean bIsStr = mA.isString("wer");   System.out.println("1:bIsStr="+bIsStr);   bIsStr = mA.isString("wer3");   System.out.println("2:bIsStr="+bIsStr);   //演示检查日期   int iIsTime = mA.chickData("2003-12-98");   System.out.println("1:iIsTime="+iIsTime);   iIsTime = mA.chickData("2003-111-08");   System.out.println("2:iIsTime="+iIsTime);   iIsTime = mA.chickData("2003-10-08");   System.out.println("3:iIsTime="+iIsTime);   iIsTime = mA.chickData("2000-02-30");   System.out.println("4:iIsTime="+iIsTime);   }   }     [JAVA100例]005、哈希表(Hashtable)和枚举器    --------------------------------------------------------------------------------    public class RoleRight   {   private static Hashtable rightList = new Hashtable();  /**   *方法说明:初始化数据   *输入参数:   *返回类型:   */   public void init()   {   String[] accRoleList = {"admin","satrap","manager","user","guest"};   String[] rightCodeList = {"10001","10011","10021","20011","24011"};   for(int i=0;i   {   rightList.put(accRoleList[i],rightCodeList[i]);   }   }  /**   *方法说明:获取角色权限代码   *输入参数:String accRole 角色名称   *返回类型:String 权限代码   */   public String getRight(String accRole)   {   if(rightList.containsKey(accRole))   return (String)rightList.get(accRole);   else   return null;   }  /**   *方法说明:添加角色和代码信息   *输入参数:String accRole 角色名称   *输入参数:String rightCode 角色权限代码    *返回类型:void (无)   */   public void insert(String accRole,String rightCode)   {   rightList.put(accRole,rightCode);   }  /**   *方法说明:删除角色权限   *输入参数:String accRole 角色名称   *返回类型:void(无)   */   public void delete(String accRole)   {   if(rightList.containsKey(accRole))   rightList.remove(accRole);   }  /**   *方法说明:修改角色权限代码   *输入参数:String accRole 角色名称   *输入参数:String rightCode 角色权限代码    *返回类型:void(无)   */   public void update(String accRole,String rightCode)   {   //this.delete(accRole);   this.insert(accRole,rightCode);   }  /**   *方法说明:打印哈希表中角色和代码对应表   *输入参数:无   *返回类型:无   */   public void print()   {   Enumeration RLKey = rightList.keys();   while(RLKey.hasMoreElements())   {   String accRole = RLKey.nextElement().toString();   print(accRole+"="+this.getRight(accRole));   }   }  /**   *方法说明:打印信息(过载)   *输入参数:Object oPara 打印的信息内容   *返回类型:无   */   public void print(Object oPara)   {   System.out.println(oPara);   }  /**   *方法说明:主方法,   *输入参数:   *返回类型:   */   public static void main(String[] args)   {   RoleRight RR = new RoleRight();   RR.init();   RR.print();   RR.print("___________________________");   RR.insert("presider","10110");   RR.print();   RR.print("___________________________");   RR.update("presider","10100");   RR.print();   RR.print("___________________________");   RR.delete("presider");   RR.print();   }    }//end:)~    [JAVA100例]006、类的继承    --------------------------------------------------------------------------------      class tree  {  /**   *方法说明:树的树根   *输入参数:   *返回类型:   */   public void root()   {   String sSite = "土壤中";   String sFunction = "吸收养份";   print("位置:"+sSite);   print("功能:"+sFunction);   }  /**   *方法说明:树的树干   *输入参数:   *返回类型:   */   public void bolo()   {   String sSite = "地面";   String sFunction = "传递养份";   print("位置:"+sSite);   print("功能:"+sFunction);   }  /**   *方法说明:树的树枝   *输入参数:   *返回类型:   */   public void branch()   {   String sSite = "树干上";   String sFunction = "传递养份";   print("位置:"+sSite);   print("功能:"+sFunction);   }  /**   *方法说明:树的叶子   *输入参数:   *返回类型:   */   public void leaf()   {   String sSite = "树梢";   String sFunction = "光合作用";   String sColor = "绿色";   print("位置:"+sSite);   print("功能:"+sFunction);   print("颜色:"+sColor);   }  /**   *方法说明:显示信息   *输入参数:Object oPara 显示的信息   *返回类型:   */   public void print(Object oPara)   {   System.out.println(oPara);   }  /**   *方法说明:主方法   *输入参数:   *返回类型:   */   public static void main(String[] arges)   {   tree t = new tree();   t.print("描述一棵树:");   t.print("树根:");   t.root();   t.print("树干:");   t.bolo();   t.print("树枝:");   t.branch();   t.print("树叶:");   t.leaf();   }  }  /**   * Title: 柳树参数   * Description: 描述柳树的参数   * Copyright: Copyright (c) 2003   * Filename:    * @author 杜江   * @version 1.0   */  class osier extends tree  {   /**   *方法说明:过载树的树叶   *输入参数:   *返回类型:   */   public void leaf()   {   super.leaf();   String sShape = "长形";   super.print("形状:"+sShape);   }   /**   *方法说明:扩展树的花   *输入参数:   *返回类型:   */   public void flower()   {   print("哈哈,柳树没有花!!");   }  /**   *方法说明:主方法   *输入参数:   *返回类型:   */   public static void main(String[] args)   {   osier o = new osier();   o.print("柳树树根:");   o.root();   o.print("柳树树干:");   o.bolo();   o.print("柳树树枝:");   o.branch();   o.print("柳树树叶:");   o.leaf();   o.print("柳树花:");   o.flower();   }  }     [JAVA100例]009、异常的捕获和实现自己的异常类    --------------------------------------------------------------------------------      /**   * Title: 捕获异常和实现自己的异常类   * Description: 通过继承Exception类来实现自己的异常类。并使用try-catch来捕获这个异常。   * Copyright: Copyright (c) 2003   * Filename:    * @version 1.0   */  class MyException extends Exception {   public MyException() {}   public MyException(String msg) {   super(msg);   }   public MyException(String msg, int x) {   super(msg);   i = x;   }   public int val() { return i; }   private int i;  }        public class DemoException {  /**   *方法说明:使用MyException类中默认的构造器   *输入参数:   *返回类型:   */   public static void a() throws MyException {   System.out.println(   "Throwing MyException from a()");   throw new MyException();   }  /**   *方法说明:使用MyException类中带信息的构造器   *输入参数:   *返回类型:   */   public static void b() throws MyException {   System.out.println(   "Throwing MyException from b()");   throw new MyException("Originated in b()");   }  /**   *方法说明:使用了MyException中有编码的构造器   *输入参数:   *返回类型:   */   public static void c() throws MyException {   System.out.println(   "Throwing MyException from c()");   throw new MyException(   "Originated in c()", 47);   }   public static void main(String[] args) {   try {   a();   } catch(MyException e) {   e.getMessage();   }   try {   b();   } catch(MyException e) {   e.toString();   }   try {   c();   } catch(MyException e) {   e.printStackTrace();   System.out.println("error code: " + e.val());   }   }  } //end :)     [JAVA100例]044、多线程服务器:每个人都有份    --------------------------------------------------------------------------------      // 文件名:moreServer.java  import java.io.*;  import java.net.*;  import java.util.*;  /**   * Title: 多线程服务器   * Description: 本实例使用多线程实现多服务功能。   * Copyright: Copyright (c) 2003   * Filename:    * @version 1.0   */  class moreServer  {   public static void main (String [] args) throws IOException   {   System.out.println ("Server starting...\n");    //使用8000端口提供服务   ServerSocket server = new ServerSocket (8000);   while (true)   {   //阻塞,直到有客户连接   Socket sk = server.accept ();   System.out.println ("Accepting Connection...\n");   //启动服务线程   new ServerThread (sk).start ();   }   }  }  //使用线程,为多个客户端服务  class ServerThread extends Thread  {   private Socket sk;      ServerThread (Socket sk)   {   this.sk = sk;   }  //线程运行实体   public void run ()   {   BufferedReader in = null;   PrintWriter out = null;   try{   InputStreamReader isr;   isr = new InputStreamReader (sk.getInputStream ());   in = new BufferedReader (isr);   out = new PrintWriter (   new BufferedWriter(   new OutputStreamWriter(   sk.getOutputStream ())), true);         while(true){   //接收来自客户端的请求,根据不同的命令返回不同的信息。   String cmd = in.readLine ();   System.out.println(cmd);   if (cmd == null)   break;   cmd = cmd.toUpperCase ();   if (cmd.startsWith ("BYE")){   out.println ("BYE");   break;   }else{   out.println ("你好,我是服务器!");   }   }   }catch (IOException e)   {   System.out.println (e.toString ());   }   finally   {   System.out.println ("Closing Connection...\n");   //最后释放资源   try{   if (in != null)   in.close ();   if (out != null)   out.close ();   if (sk != null)   sk.close ();   }   catch (IOException e)   {   System.out.println("close err"+e);   }   }   }  }                          //文件名:SocketClient.java  import java.io.*;  import java.net.*;   class SocketThreadClient extends Thread  {   public static int count = 0;  //构造器,实现服务   public SocketThreadClient (InetAddress addr)   {   count++;   BufferedReader in = null;   PrintWriter out = null;   Socket sk = null;   try{   //使用8000端口   sk = new Socket (addr, 8000);   InputStreamReader isr;   isr = new InputStreamReader (sk.getInputStream ());   in = new BufferedReader (isr);   //建立输出   out = new PrintWriter (   new BufferedWriter(   new OutputStreamWriter(   sk.getOutputStream ())), true);   //向服务器发送请求   System.out.println("count:"+count);   out.println ("Hello");   System.out.println (in.readLine ());   out.println ("BYE");   System.out.println (in.readLine ());         }   catch (IOException e)   {   System.out.println (e.toString ());   }   finally   {   out.println("END");   //释放资源   try   {   if (in != null)   in.close ();   if (out != null)   out.close ();   if (sk != null)   sk.close ();   }   catch (IOException e)   {   }   }   }  }  //客户端  public class SocketClient{   public static void main(String[] args) throws IOException,InterruptedException   {   InetAddress addr = InetAddress.getByName(null);   for(int i=0;i<10;i++)   new SocketThreadClient(addr);   Thread.currentThread().sleep(1000);   }   }       [JAVA100例]058、调用存储过程    --------------------------------------------------------------------------------      import java.sql.*;        /**   * Title: JDBC连接数据库   * Description: 本实例演示如何使用JDBC连接Oracle数据库,并演示添加数据和查询数据。   * Copyright: Copyright (c) 2003   * Filename: JDBCSTMConn.java   * @version 1.0   */  public class JDBCSTMConn{   private static String url="";   private static String username="";   private static String password="";  /**   *方法说明:获得数据连接   *输入参数:   *返回类型:Connection 连接对象   */    public Connection conn(){   try {   //加载JDBC驱动   Class.forName("oracle.jdbc.driver.OracleDriver");   //创建数据库连接   Connection con = DriverManager.getConnection(url, username, password);   return con;   }catch(ClassNotFoundException cnf){   System.out.println("driver not find:"+cnf);   return null;   }catch(SQLException sqle){   System.out.println("can´t connection db:"+sqle);   return null;   } catch (Exception e) {   System.out.println("Failed to load JDBC/ODBC driver.");   return null;   }   }  /**   *方法说明:调用存储过程,察看数据结果   *输入参数:Connection con 数据库连接   *输入参数:String sql 要执行的SQL语句   *返回类型:   */   public void execute(Connection con){   CallableStatement toesUp = null;    try {    con.setAutoCommit(false);    //调用存储过程   toesUp = con.prepareCall("{call p_test(?)}");    //传递参数给存储过程   toesUp.setInt(1, 6);   //执行存储过程   toesUp.executeQuery();         Statement stmt = con.createStatement();   ResultSet rs = (ResultSet) stmt.executeQuery("SELECT * FROM TEST");    while (rs.next()) {    String ID = rs.getString(1);    String NAME = rs.getString(2);    System.out.println(ID+ " " +NAME);   }    rs.close();    } catch (SQLException e) {    System.out.println(e);   try{   toesUp.close();    con.close();   }catch(Exception es){System.out.println(es);}    }   }        /**   *方法说明:实例演示   *输入参数:   *返回类型:   */   public void demo(){   try{   JDBCSTMConn oc = new JDBCSTMConn();   Connection conn = oc.conn();   oc.execute(conn);   conn.close();   }catch(SQLException se){   System.out.println(se);   }catch(Exception e){   System.out.println(e);   }      }  /**   *方法说明:主方法   *输入参数:   *返回类型:   */   public static void main(String[] arg){   if(arg.length!=3){   System.out.println("use: java JDBCSTMConn url username password");   return;   }   JDBCSTMConn oc = new JDBCSTMConn();   oc.url = arg[0];   oc.username=arg[1];   oc.password=arg[2];   oc.demo();   }  }      [JAVA100例]059、事务处理    --------------------------------------------------------------------------------      import java.sql.*;  /**   * Title: JDBC连接数据库   * Description: 本实例演示如何使用JDBC连接Oracle数据库,并演示添加数据和查询数据。   * Copyright: Copyright (c) 2003   * Filename: JDBCConnCommit.java   * @version 1.0   */  public class JDBCConnCommit{   private static String url="";   private static String username="";   private static String password="";  /**   *方法说明:获得数据连接   *输入参数:   *返回类型:Connection 连接对象   */    public Connection conn(){   try {   //加载JDBC驱动   Class.forName("oracle.jdbc.driver.OracleDriver");   //创建数据库连接   Connection con = DriverManager.getConnection(url, username, password);   return con;   }catch(ClassNotFoundException cnf){   System.out.println("driver not find:"+cnf);   return null;   }catch(SQLException sqle){   System.out.println("can´t connection db:"+sqle);   return null;   } catch (Exception e) {   System.out.println("Failed to load JDBC/ODBC driver.");   return null;   }   }        /**   *方法说明:执行查询SQL语句   *输入参数:Connection con 数据库连接   *输入参数:String sql 要执行的SQL语句   *返回类型:   */   public void query(Connection con, String sql) throws SQLException,Exception {   try{   if(con==null){   throw new Exception("database connection can´t use!");   }   if(sql==null) throw new Exception("check your parameter: ´sql´! don´t input null!");   //声明语句   Statement stmt = con.createStatement();   //执行查询   ResultSet rs = stmt.executeQuery(sql);    ResultSetMetaData rmeta = rs.getMetaData();   //获得数据字段个数   int numColumns = rmeta.getColumnCount();   while(rs.next())   {   for(int i = 0;i< numColumns;i++)   {   String sTemp = rs.getString(i+1);   System.out.print(sTemp+" ");   }   System.out.println("");    }   rs.close();   stmt.close();   }catch(Exception e){   System.out.println("query error: sql = "+sql);   System.out.println("query error:"+e);   throw new SQLException("query error");   }   }  /**   *方法说明:执行插入、更新、删除等没有返回结果集的SQL语句   *输入参数:Connection con 数据库连接   *输入参数:String sql 要执行的SQL语句   *返回类型:   */   public void execute(Connection con, String sql) throws SQLException {   try{   if(con==null) return;   Statement stmt = con.createStatement();   int i = stmt.executeUpdate(sql);    System.out.println("update row:"+i);   stmt.close();   }catch(Exception e){   System.out.println("execute error: sql = "+sql);   System.out.println(e);   throw new SQLException("execute error");   }   }        /**   *方法说明:实例演示   *输入参数:   *返回类型:   */   public void demo(){   JDBCConnCommit oc = new JDBCConnCommit();   Connection conn = oc.conn();   try{   conn.setAutoCommit( false );   String sql = "";   for(int i=0;i<4;i++){   sql = "insert into TBL_USER(id,name,password)values(seq_user.nextval,´tom´,´haorenpingan´)";   oc.execute(conn,sql);   }   sql = "select * from TBL_USER where name=´tom´ order by id";   oc.query(conn,sql);   sql = "delete from TBL_USER where name=´tom´";   oc.execute(conn,sql);   conn.commit();   }catch(SQLException se){   try{   conn.rollback();    }catch(Exception e){   }   System.out.println(se);   }catch(Exception e){    System.out.println(e);   }finally   {    try{   conn.close();   }catch(SQLException e){}   }      }  /**   *方法说明:主方法   *输入参数:   *返回类型:   */   public static void main(String[] arg){   if(arg.length!=3){   System.out.println("use: java JDBCConnCommit url username password");   return;   }   JDBCConnCommit oc = new JDBCConnCommit();   oc.url = arg[0];   oc.username=arg[1];   oc.password=arg[2];   oc.demo();   }  }   [JAVA100例]060、继承Thread    --------------------------------------------------------------------------------    /**   * Title: 继承Thread,实现线程   * Description: 通过继承Thread类,实现其run方法,实现自己的线程   * Copyright: Copyright (c) 2003   * Filename: oneThread.java   * @version 1.0   */  public class oneThread extends Thread {  /**   *方法说明:构造器,本类没有使用   *输入参数:   *返回类型:   */  public oneThread() {      }  /**   *方法说明:继承Thread类必须实现的方法,当调用start方法时运行本方法   *输入参数:   *返回类型:   */   public void run() {   System.out.println("...............oneThread begining................");   int flag = 0;   while(true) {   if(flag==20){   System.out.println("\n...............oneThread end............. ");   break;   }   for(int i=0;i   System.out.print("*");   System.out.println("");   flag++;   try{   //睡眠0.1秒   sleep(100);   }catch(Exception e){   }    }   }  /**   *方法说明:主方法。启动本线程   *输入参数:   *返回类型:   */   public static void main(String args[]) {   new oneThread().start();   }  }  [JAVA100例]061、实现Runnable    --------------------------------------------------------------------------------    /**   * Title: 实现Runnable接口,获得线程。   * Description: 通过实现Runnable接口来获得自己的线程(t2)。   * Copyright: Copyright (c) 2003   * Filename: twothread.java   * @version 1.0   */  public class twothread implements Runnable {  /**   *方法说明:构造器。实际线程,并启动这个线程。   *输入参数:   *返回类型:   */   twothread() {    //获取当前的线程   Thread t1 =Thread.currentThread();    t1.setName("The first main thread");    System.out.println("The running thread:" + t1);    //通过将本类(Runnable接口)和名称构造一个线程   Thread t2 = new Thread(this,"the second thread");    System.out.println("creat another thread");    //启动线程   t2.start();    try {    System.out.println("first thread will sleep");    Thread.sleep(3000);    }catch (InterruptedException e) {   System.out.println("first thread has wrong");    }    System.out.println("first thread exit");    }   /**   *方法说明:线程主体。实现run方法。   *输入参数:   *返回类型:   */   public void run() {    try {    for (int i=0;i<5;i++) {    System.out.println("Sleep time for thread 2:"+i);    Thread.sleep(1000);    }   } catch (InterruptedException e) {   System.out.println("thread has wrong");    }   System.out.println("second thread exit");    }   /**   *方法说明:主方法   *输入参数:   *返回类型:   */   public static void main(String args[]) {    new twothread();    }   }    [JAVA100例]062、多线程    --------------------------------------------------------------------------------    /**   * Title: 创建多线程   * Description: 使用构造器,创建多线程。   * Copyright: Copyright (c) 2003   * Filename: multiThread.java   * @version 1.0   */  public class multiThread   {   /**   *方法说明:主方法   *输入参数:   *返回类型:   */   public static void main (String [] args){    new multiThread();   }  /**   *方法说明:构造器。构造多个线程,并启动它们。   *输入参数:   *返回类型:   */   multiThread(){   for (int i = 0; i < 5; i++){   System.out.println("Creating thread "+i);   innThread mt = new innThread (i);    mt.start ();    }   }  /**   *类说明:内部类通过继承Thread实现线程    *类描述:通过构造器参数,区别不同的线程   */    class innThread extends Thread    {    int count;   innThread(int i){   count=i;   }  /**   *方法说明:内部类线程主体,继承Thread必须实现的方法。   *输入参数:   *返回类型:   */   public void run ()    {    System.out.println("now "+count+" thread is beginning..... ");   try{   sleep(10-count);   }catch(Exception e){   System.out.println(e);   }   System.out.println("\n"+count+" thread is end!");   }    }   }    [JAVA100例]063、线程群组    --------------------------------------------------------------------------------    /**   * Title: 线程组群   * Description: 通过线程组管理下面的多个线程。   * Copyright: Copyright (c) 2003   * Filename: myThreadgroup.java   * @version 1.0   */  public class myThreadgroup extends Thread {   public static int flag=1;   ThreadGroup tgA;   ThreadGroup tgB;  /**   *方法说明:主方法   *输入参数:   *返回类型:   */   public static void main(String[] args){   myThreadgroup dt = new myThreadgroup();   //声明线程组A   dt.tgA = new ThreadGroup("A");   //声明线程组B   dt.tgB = new ThreadGroup("B");   for(int i=1;i<3;i++)   new thread1(dt.tgA,i*1000,"one"+i);   for(int i=1;i<3;i++)   new thread1(dt.tgB,1000,"two"+i);   //启动本线程和所有线程组   dt.start();   }  /**   *方法说明:覆盖run方法,控制线程组   *输入参数:   *返回类型:   */   public void run(){   try{   this.sleep(5000);   this.tgB.checkAccess();   //停止线程组B,   this.tgB.stop();   System.out.println("**************tgB stop!***********************");   this.sleep(1000);   //检查线程组A是否可以更改   this.tgA.checkAccess();   //停止线程组A   this.tgA.stop();   System.out.println("**************tgA stop!***********************");      }catch(SecurityException es){   System.out.println("**"+es);   }catch(Exception e){   System.out.println("::"+e);   }   }  }  /**   * Title: 线程类   * Description: 通过构造器的参数,实现不同的线程   * Copyright: Copyright (c) 2003   * Filename: thread1.java   * @author 杜江   * @version 1.0   */  class thread1 extends Thread {   int pauseTime;   String name;   public thread1(ThreadGroup g,int x, String n) {   super(g,n);   pauseTime = x;   name = n;   start();   }  /**   *方法说明:必须覆盖的方法。   *输入参数:   *返回类型:   */   public void run ()    {   while(true) {   try {   System.out.print(name+"::::");   this.getThreadGroup().list();//获取线程组信息   Thread.sleep(pauseTime);   } catch(Exception e) {   System.out.println(e);   }   }   }  }  [JAVA100例]064、线程间通讯    --------------------------------------------------------------------------------    /**   * Title: 线程间合作   * Description: 本实例使用二个线程共同合作绘制一个实体三角。   * Copyright: Copyright (c) 2003   * Filename: mainThread.java   * @version 1.0   */  public class mainThread{   public static int flag = 0;   int count = 10;  /**   *方法说明:主方法   *输入参数:   *返回类型:   */   public static void main(String[] arg){   new mainThread();   }  /**   *方法说明:构造器,启动两个子线程。   *输入参数:   *返回类型:   */   mainThread(){   thread1 t1 = new mainThread.thread1(this.count);   thread2 t2 = new mainThread.thread2(this.count);   //启动两线程   t1.start();   t2.start();   //让线程一首先工作。   flag = 1;   }  /**   *类说明:内部类,继承了Thread,   *类描述:实现了在输出每行前面的空格。   */   class thread1 extends Thread{   int count1 = 0;    thread1(int i){   count1 = i;   }   public void run(){      while(true){   if(count1<=0) break;   if(mainThread.flag==1){      for(int i=0;i   System.out.print(" ");   }   count1--;   mainThread.flag=2;   }   }   }   }  /**   *类说明:内部类,继承了Thread,   *类描述:实现了在输出每行第“*”号。并提供换行。   */   class thread2 extends Thread{   int count2 = 0;    thread2(int i){   count2 = i;   }   public void run(){   int count = 0;   while(true){   if(count>=count2) break;   if(mainThread.flag==2){   for(int i=0;i<(count*2+1);i++){   System.out.print("*");   }   System.out.print("\n");   count++;   mainThread.flag=1;   }   }   }   }   }    [JAVA100例]065、线程同步    --------------------------------------------------------------------------------      /**   * Title: 线程同步   * Description: 通过使用同步锁实现对共享数据的操作   * Copyright: Copyright (c) 2003   * Filename: SyThreadDemo.java   * @version 1.0   */  /**   *类说明:主程序   *功能描述:构造两个线程,并启动它们   */  public class SyThreadDemo   {    public static void main (String [] args)    {    trade ft = new trade ();    addThread tt1 = new addThread (ft, "add");    decThread tt2 = new decThread (ft, "dec");    tt1.start ();    tt2.start ();    }   }  /**   *类说明:同步类   *功能描述:保存共享数据,   */  class trade   {    private String transName;    private double amount;   /**   *方法说明:更新数据   *输入参数:String transName 操作名称   *输入参数:double amount 资金数量   *返回类型:   */   synchronized void update (String transName, double amount)    {    this.transName = transName;    this.amount = amount;    System.out.println (this.transName + " " + this.amount);    }   }   /**   *类说明:添加资金   *功能描述:单线程,调用trade.update()方法,修改数据   */  class addThread extends Thread   {    private trade ft;    addThread (trade ft, String name)    {    super (name);   this.ft = ft;    }    public void run ()    {    for (int i = 0; i < 10; i++)    ft.update ("add", 2000.0);    }   }   /**   *类说明:减少资金   *功能描述:单线程,调用trade.update()方法,修改数据   */  class decThread extends Thread   {    private trade fd;    decThread (trade fd, String name)    {    super (name);   this.fd = fd;    }   /**   *方法说明:线程主体   *输入参数:   *返回类型:   */   public void run ()    {    for (int i = 0; i < 10; i++)    fd.update ("dec", -2000.0);          }   }   [JAVA100例]066、线程控制    --------------------------------------------------------------------------------      /**   * Title: 线程控制   * Description: 实现对线程的控制,中断、挂起、恢复、停止   * Copyright: Copyright (c) 2003   * Filename: threadCtrl.java   * @version 1.0   */  public class threadCtrl{   public static void main(String [] main){   new threadCtrl();   }  /**   *方法说明:构造器,控制其它线程   *输入参数:   *返回类型:   */   threadCtrl(){   try{   Thread tm = Thread.currentThread();   threadchild td = new threadchild();   td.start();   tm.sleep(500);   System.out.println("interrupt child thread");   td.interrupt();         System.out.println("let child thread wait!");   //td.wait();   //td.suspend();   tm.sleep(1000);         System.out.println("let child thread working");   td.fauxresume();   //td.resume();   tm.sleep(1000);   td.runflag = false;   System.out.println("main over..............");   }catch(InterruptedException ie){   System.out.println("inter main::"+ie);   }catch(Exception e){   System.out.println("main::"+e);   }   }        }  /**   *类说明:被控线程类   */   class threadchild extends Thread {   boolean runflag = true;   boolean suspended = true;   threadchild(){   }   public synchronized void fauxresume(){   suspended = false;   notify();   }    public void run(){   while(runflag){   System.out.println("I am working..............");   try{   sleep(1000);   }catch(InterruptedException e){   System.out.println("sleep::"+e);   }   synchronized(this){   try{   if(suspended)   wait();   }catch(InterruptedException e){   System.out.println("wait::"+e);   }   }   }   System.out.println("thread over...........");   }   }     [JAVA100例]067、线程优先级    --------------------------------------------------------------------------------      import java.util.*;  /**   * Title: 提高线程优先级   * Description: 通过修改线程的优先级,是线程获得优先处理。   * Copyright: Copyright (c) 2003   * Filename: upPRIThread.java   * @version 1.0   */  public class upPRIThread {   //主方法   public static void main(String[] args) throws Exception {   Thread1 t1 = new Thread1();   t1.start();   Thread2 t2 = new Thread2();   t2.start();   t1.setPriority(Thread.MIN_PRIORITY);   t2.setPriority(Thread.MIN_PRIORITY);   new Thread().sleep(105);   t2.setPriority(Thread.MAX_PRIORITY);   new Thread().sleep(10500);   }   //类说明:线程1,不更改优先级   static class Thread1 extends Thread {   public void run(){   while(true){   try {   Thread.sleep(100);   }    catch (Exception e){   e.printStackTrace();   }   System.out.println("我是线程111");   }   }   }   //类说明:线程2,提高优先级   static class Thread2 extends Thread {         public void run(){   while(true){   try {   Thread.sleep(100);   }    catch (Exception e){   e.printStackTrace();   }   System.out.println("我是线程222.........................");   }   }   }  }


 

原创粉丝点击