1、两个线程实现奇数偶数计算
package Ex4.Firstquestion;
public class Main {
public static final int DELAY = 100;
public static void main(String[] args) {
Compute compute = new Compute(1, 100);
Runnable task1 = () ->{
try{
compute.oddCompute(compute.from,compute.to);
Thread.sleep((int)(DELAY*Math.random()));
}catch (InterruptedException e){
e.printStackTrace();
}
};
Runnable task2 = () ->{
try{
compute.evenCompute(compute.from,compute.to);
Thread.sleep((int)(DELAY*Math.random()));
}catch (InterruptedException e){
e.printStackTrace();
}
};
new Thread(task1).start();
new Thread(task2).start();
}
}
class Compute{
public int from = 1;
public int to = 100;
Compute(int from,int to){
this.from = from;
this.to = to;
}
public void oddCompute(int from,int to){
int numOfOdd = 0;
for(int i = from; i <= to; i++){
if(i % 2 == 1) {
numOfOdd++;
System.out.println("第" + numOfOdd + "个奇数为:" + i);
}
}
}
public void evenCompute(int from,int to){
int numOfEven = 0;
for(int i = from; i <= to; i++){
if(i % 2 == 0) {
numOfEven++;
System.out.println("第" + numOfEven + "个偶数为:" + i);
}
}
}
}
![在这里插入图片描述]()
1、一个线程实现奇数偶数计算
package Ex4.Firstquestion;
public class NewMain {
public static final int FROM = 1;
public static final int TO = 100;
public static void main(String[] args) {
ComputeOfNew computeOfNew = new ComputeOfNew(FROM,TO);
Thread thread = new Thread(computeOfNew);
thread.start();
}
}
class ComputeOfNew implements Runnable{
public static int numOfOdd = 0;
public static int numOfEven = 0;
private int from;
private int to;
ComputeOfNew(int FROM,int TO){
this.from = FROM;
this.to = TO;
}
public void compute(int value){
if(value % 2 != 0) {
System.out.println("第 " + (++numOfOdd) + " 个奇数为:" + value);
}
else{
System.out.println("第 " + (++numOfEven) + " 个偶数为:" + value);
}
}
@Override
public void run() {
for(int i = this.from; i <= this.to; i++){
compute(i);
}
}
}
![在这里插入图片描述]()
2、补全代码
package Ex4.Secondquestion;
class Tortoise extends Thread
{
int sleepTime = 0;
int liveLength = 0;
public Tortoise(String name,int sleepTime, int liveLength)
{
this.sleepTime=sleepTime;
this.liveLength=liveLength;
this.setName(name);
}
@Override
public void run()
{
while (true ) {
liveLength--;
System.out.println("@_@");
try{
Thread.sleep(sleepTime);
}
catch (InterruptedException e) {
}
if (liveLength <= 0 ) {
System.out.println(getName()+"进入死亡状态\n");
break;
}
}
}
}
class Rabit extends Thread
{
int sleepTime=0;
int liveLength=0;
public Rabit(String name,int sleepTime, int liveLength)
{
super(name);
this.sleepTime=sleepTime;
this.liveLength=liveLength;
}
@Override
public void run()
{
while (true)
{
liveLength--;
System.out.println("*_*");
try{
sleep( sleepTime);
}
catch (InterruptedException e) {}
if (liveLength<=0)
{
System.out.println(getName() + "进入死亡状态\n");
break;
}
}
}
}
public class ThreadExample
{
public static void main(String a[])
{
Rabit rabit;
rabit = new Rabit("rabit",15,55);
Tortoise tortoise = new Tortoise("tortoise",20,50);
tortoise.start();
rabit.start();
}
}
![在这里插入图片描述]()