public class thread extends Thread{ static int i=1; @Override public void run() { Thread.yield(); while(true) { if(method()){ break; } } } public static synchronized boolean method(){ try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } if(i<100){ if(i%2!=0) { System.out.println(currentThread().getName()+i); } i++; return false; } return true; } }为什么该代码的线程只进不出
时间: 2024-02-10 09:19:08 浏览: 28
在这段代码中,线程调用了`Thread.yield()`方法,这个方法会让当前线程放弃 CPU,让其他线程有机会执行。但是这个方法并不保证一定会让出 CPU,有可能当前线程仍然会继续执行。在这个例子中,线程进入了`while(true)`循环,如果`method()`方法返回`false`,那么线程会继续执行下去。因为这个方法中有一个`synchronized`关键字,所以只有一个线程能够进入这个方法执行。如果这个线程一直在执行这个方法,那么其他线程就会一直等待,从而导致“线程只进不出”的情况。
相关问题
ublic class Jiecheng{ public static void main(String[] args){ Jiecheng1 a = new Jiecheng1(5); thread.start(); } class Jiecheng1 extends Thread{ int num; public Jiecheng1(int num){ this.num = num; } } @Override public void run(){ int i = num; int result = 1; while(i > 0){ result = i * result ; i = i - 1 ; } } }修改这个代码
您的代码存在一些语法错误,已经进行了一些修改:
```
public class Jiecheng {
public static void main(String[] args) {
Jiecheng1 a = new Jiecheng1(5);
a.start();
}
static class Jiecheng1 extends Thread {
int num;
public Jiecheng1(int num) {
this.num = num;
}
@Override
public void run() {
int i = num;
int result = 1;
while (i > 0) {
result = i * result;
i = i - 1;
}
System.out.println(result);
}
}
}
```
主要的修改包括:
1. 将 `class Jiecheng1` 修改为 `static class Jiecheng1`,因为在 `main` 方法中直接使用了该内部类,必须是 `static` 的。
2. 将 `thread.start()` 修改为 `a.start()`,因为 `thread` 未定义,应该使用对象 `a` 调用 `start()` 方法。
3. 在 `run()` 方法中添加了一行 `System.out.println(result)`,输出结果。
该程序的功能是计算一个数的阶乘,并输出结果。在 `main` 方法中创建了一个 `Jiecheng1` 对象 `a`,并传入参数 `5`。然后调用 `a.start()` 方法启动一个新的线程,在该线程中执行阶乘计算并输出结果。
写出下列程序运行结果:class Base{ Base() { int i = 100; System. out. println(i); } } public class Pri extends Base{ static int i = 200; public static void main(Stringargv[]){ Pri p = new Pri();System. out.println(i); } }
程序的运行结果为:
```
100
200
```
解释:这段程序定义了一个基类Base和一个派生类Pri,Pri继承自Base。在Pri的main方法中创建了一个Pri对象p。创建对象时,先调用父类Base的构造方法,输出100。然后输出Pri类中的静态变量i的值200。