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基础

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。