我的代码现在是这样的:Urlprint sa = new Urlprint();
sa.start();
while (true) {
if(...)
{
}
else if("s".equalsIgnoreCase(line))
{
//按键盘s+回车手动终止线程sa
sa.isrun = false;
//下面是手动终止后的代码,我就省略了。
}
}我现在想写的就是,如果线程自己运行结束了,也要做手动运行结束同样的事。看起来挺简单的,但是我还实现不了。因为好像while外面不能加其他代码了,也希望有高手能给我解释下为什么不能写代码在while(true)这个loop外面,还有while(true)是起什么作用的!谢谢!
sa.start();
while (true) {
if(...)
{
}
else if("s".equalsIgnoreCase(line))
{
//按键盘s+回车手动终止线程sa
sa.isrun = false;
//下面是手动终止后的代码,我就省略了。
}
}我现在想写的就是,如果线程自己运行结束了,也要做手动运行结束同样的事。看起来挺简单的,但是我还实现不了。因为好像while外面不能加其他代码了,也希望有高手能给我解释下为什么不能写代码在while(true)这个loop外面,还有while(true)是起什么作用的!谢谢!
楼主初学,要加油哦!OVER
但是好像不用while(true)还不行?
另外我想在线程自动结束后 写代码,请问应该怎么写呢?
换为以下代码就可以手动结束了:
sa.isrun = true;
while(sa.isrun)
while(true){
//执行正常逻辑的代码
.....
list.add(Object);
.....
if("s".equalsIgnoreCase(line)){
//如果按了"s"键,退出循环
break;
}
}
//退出while循环后,遍历list,打印结果
for(int i=0;i<list.size;i++){
//do something
}
你可以做俩个循环
List list = new ArrayList();
boolean flag=true;
while(flag){
while(true){
//这里是你要干的事
list.add(Object);
if("s".equalsIgnoreCase(line)){
//如果按了"s"键,退出循环
flag=false;
break;
}
}
//到此时内loop终止,可以对list遍历
for(int i=0;i<list.size;i++){
//do something
}}
static boolean isrun = true;
public static void main(String[] args) throws IOException, InterruptedException {
TestThread1 t = new TestThread1();
t.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while(true)
{
while (isrun) {
line = reader.readLine();
System.out.println("line=" + line);
if ("p".equalsIgnoreCase(line)) {
t.pause = true;
}
else {
t.pause = false;
t.interrupt();
synchronized (t) { //
t.notifyAll();
}
}
}
System.out.println("finished");
}
}
}
class TestThread1 extends Thread {
boolean pause;
boolean isrun = true;
public void run() {
try {
if (pause) {
synchronized (this) {
wait();
}
}
for(int i=0; i<10; i++)
{
System.out.println(i);
}
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("interrupted...");
}
//}
}
}不重要的就不用看了,这个老紫竹昨天给我的暂停的代码,我想在这个线程结束后 print个"finished",但是这个都实现不了,这个线程应该就是从0打印到9啊。请问怎么改才能让线程结束后打印或者干别的呢?很着急啊。给这个问题烦了2天了!
摆脱各位高手!
你这个基本上是死循环了吧 在合适的地方加个isrun=false;
while (isrun) {
line = reader.readLine();
System.out.println("line=" + line);
if ("p".equalsIgnoreCase(line)) {
t.pause = true;
}
else {
t.pause = false;
t.interrupt();
synchronized (t) { //
t.notifyAll();
}
}
}
我现在想要自动终止,然后继续写啊..