#Java编程# 编写一个应用程序创建两个线程,一个线程打印输出1~100之间所有的奇数,另外一

2024-11-22 16:43:33
推荐回答(2个)
回答1:

import java.util.Random;

class A extends Thread
{
int i=1;
Random r=new Random();
public void run()
{
while(i<100)
{
System.out.println("奇数:"+i);
i+=2;
try
{
Thread.sleep(r.nextInt(500));
}
catch(InterruptedException e)
{
e.printStackTrace();
};
}
}
}
class B implements Runnable
{
int i=2;
Random r=new Random();
public void run()
{
while(i<=100)
{
System.out.println("偶数:"+i);
i+=2;
try
{
Thread.sleep(r.nextInt(500));
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
public class TestThread
{
public static void main(String[] args)
{
new A().start();
new Thread(new B()).start();
}
}

回答2:

这个我可以给你写哦,主要是线程间同步与互斥。RUNNABLE接口实现及thread继承