实例一: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);
}
}