您的位置:首页 > 编程语言 > Java开发

使Java线程停止的两种方法

2017-08-02 00:00 381 查看
package Thread;

public class testthread {

public static void main(String[] args) {
asdf t = new asdf();
Thread tt = new Thread(t,"线程1");
tt.start();

try {                                           //主线程休眠10秒,
tt.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tt.interrupt();         //主线程打断.

}

}

class asdf implements Runnable{

public void run() {
int i = 1;
boolean b = true;
while(b){

  System.out.println(Thread.currentThread().getName().toString()+i);

  i++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block

break;
}

}

}
}

改变while中的条件

package Thread;

public class testthread {

public static void main(String[] args) {
asdf t = new asdf();
Thread tt = new Thread(t,"线程1");

 
tt.start();
 
}

}

class asdf implements Runnable{

public void run() {
int i = 1;

boolean b = true;
while(b){

   

  if(i==10){

  b = false;

  }

  System.out.println(Thread.currentThread().getName().toString()+i);

  i++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: