683
1、当其他非守护线程完成时,守护线程将自行结束。
2、任何线程都可以成为守护线程。通过调用Thread.setdaemon()来声明一个线程是一个守护线程。线程的共性是只有在非守护线程还在工作时才有意义。
实例
/**
*Createstenthreadstosearchforthemaximumvalueofalargematrix.
*Eachthreadsearchesoneportionofthematrix.
*/
publicclassTenThreads{
privatestaticclassWorkerThreadextendsThread{
intmax=Integer.MIN_VALUE;
int[]ourArray;
publicWorkerThread(int[]ourArray){
this.ourArray=ourArray;
//Findthemaximumvalueinourparticularpieceofthearray
publicvoidrun(){
for(inti=0;i<ourArray.length;i++)
max=Math.max(max,ourArray[i]);
publicintgetMax(){
returnmax;
publicstaticvoidmain(String[]args){
WorkerThread[]threads=newWorkerThread[10];
int[][]bigMatrix=getBigHairyMatrix();
intmax=Integer.MIN_VALUE;
//Giveeachthreadasliceofthematrixtoworkwith
for(inti=0;i<10;i++){
threads[i]=newWorkerThread(bigMatrix[i]);
threads[i].start();
//Waitforeachthreadtofinish
try{
for(inti=0;i<10;i++){
threads[i].join();
max=Math.max(max,threads[i].getMax());
catch(InterruptedExceptione){
//fallthrough
System.out.println("Maximumvaluewas"+max);
以上就是java守护线程的理解,希望对大家有所帮助。更多Java学习指路:Java基础