设为首页 加入收藏

TOP

Java线程操作实例
2014-11-16 19:00:35 来源: 作者: 【 】 浏览:29
Tags:Java 线程 操作 实例

  实例一:10秒钟之内循环输出


  package theardtest;


  import java.util.logging.Level;


  import java.util.logging.Logger;


  /**


  *


  * @author Wei.Liu


  */


  public class Main extends Thread {


  /**


  * @param args the command line arguments


  */


  public volatile boolean finished = false;


  public void run(){


  int i=0;


  while(!finished){


  System.out.println(i);


  i++;


  }


  }


  public static void main(String[] args) {


  // TODO code application logic here


  Main temp = new Main();


  temp.start();


  try {


  Thread.sleep(10000);//


  } catch (InterruptedException ex) {


  Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);


  }


  temp.finished=true;


  }


  实例二:开10个线程寻找2维数组中的最大值


  package threadtest;


  import java.util.logging.Level;


  import java.util.logging.Logger;


  /**


  *


  * @author Wei.Liu


  */


  public class Main {


  static class WorkThread extends Thread{


  int max=Integer.MIN_VALUE;


  int [] ourArray;


  public void setArray(int [] ourArray){


  this.ourArray = ourArray;


  }


  @Override


  public void run(){


  for(int i=0;i<ourArray.length;i++){


  max = Math.max(max, ourArray[i]);


  }


  }


  public int getMax(){


  return max;


  }


  }


  public static void main(String [] args){


  WorkThread [] temp =new WorkThread[10];


  int [][]bigMatrix = {{2,12,5,9,42,12,5,9,4,12},{5,25,895,632,2},{111,0,15,45},{56,2},{4525,2,1},{12,12,12},{1,21,3},{12,1,2,3},{45,251,25,4},{15421524,251,458,26542,4865221,5624}};


  int max = Integer.MIN_VALUE;


  for(int i=0;i<10;i++){


  temp[i]= new WorkThread();


  temp[i].setArray(bigMatrix[i]);


  temp[i].start();


  }


  //Wait for each thread to finished


  try{


  for(int i=0;i<10;i++){


  temp[i].join();


  max = Math.max(max, temp[i].getMax());


  }}catch(Exception e){


  e.printStackTrace();


  }


  System.out.println("Max value:::"+max);


  }


  }


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java上传文件(简单例子) 下一篇Java中ArrayList或Collection的co..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: