小弟初学线程,请指教!
我首先调用主线程启动A线程,然后通过Thread.yield()方法使主线程暂停后,则执行的是A线程,等A线程时间片到期后应该继续主线程来启动B线程,此时主线程结束,接下来A,B线程应该交替执行啊,可为什么打印出来的就只有A线程?
代码如下:
public class Test {
public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt,"A").start();
Thread.yield();
mt.b=true;
new Thread(mt,"B").start();
}
}class MyThread implements Runnable {
int num=100;
Object o=new Object();
boolean b=false;
public void minus() {
while(true) {
synchronized(o) {
if(num>0) {
try {
Thread.sleep(50);
}catch(InterruptedException ie) {
ie.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+" "+num);
num--;
}else {
System.exit(0);
}
}
}
}
public synchronized void run() {
if(b==false) {
minus();
}else {
while(true) {
if(num>0) {
try {
Thread.sleep(50);
}catch(InterruptedException ie) {
ie.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+" "+num);
num--;
}else {
System.exit(0);
}
}
}
}
}
我首先调用主线程启动A线程,然后通过Thread.yield()方法使主线程暂停后,则执行的是A线程,等A线程时间片到期后应该继续主线程来启动B线程,此时主线程结束,接下来A,B线程应该交替执行啊,可为什么打印出来的就只有A线程?
代码如下:
public class Test {
public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt,"A").start();
Thread.yield();
mt.b=true;
new Thread(mt,"B").start();
}
}class MyThread implements Runnable {
int num=100;
Object o=new Object();
boolean b=false;
public void minus() {
while(true) {
synchronized(o) {
if(num>0) {
try {
Thread.sleep(50);
}catch(InterruptedException ie) {
ie.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+" "+num);
num--;
}else {
System.exit(0);
}
}
}
}
public synchronized void run() {
if(b==false) {
minus();
}else {
while(true) {
if(num>0) {
try {
Thread.sleep(50);
}catch(InterruptedException ie) {
ie.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+" "+num);
num--;
}else {
System.exit(0);
}
}
}
}
}
比如把minus()方法中的while(true)放到
if(b==false) {
minus();
中去
已经终止当前正在运行的 Java 虚拟机,试问怎么会执行线程B呢
class MyThread implements Runnable {
int num=10;
Object o=new Object();
boolean b=false;
public void minus() {
while(true) {
synchronized(o) {
if(num>5) {
try {
Thread.sleep(50);
}catch(InterruptedException ie) {
ie.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+" "+num);
num--;
}else {
//System.exit(0);
break;
}
}
}
}
public synchronized void run() {
if(b==false) {
minus();
}else {
while(true) {
if(num>0) {
try {
Thread.sleep(50);
}catch(InterruptedException ie) {
ie.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+" "+num);
num--;
}else {
System.exit(0);
}
}
}
}
}
public class Test {
public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt,"A").start();
Thread.yield();
mt.b=true;
new Thread(mt,"B").start();
System.out.println("C");
}
}
为什么先打印的是C也就是在main线程执行完之后再执行线程A,但应该是main线程执行到Thread.yield()的时候就应该暂停转而执行线程A啊