Java作业5 多线程
1. 判断
下面哪些方法是java.lang.Thread类中的方法?哪些方法是能抛出异常InterruptedException的?哪些方法在Java中是禁用的?
run(), start(), stop(), suspend(), resume(), sleep(), interrupt(), yield(), join()
答: 方法:run()、start()、stop()、suspend()、resume()、interrupt()、yield()、join() 能抛出异常InterruptedException的:sleep()、join()、 禁用:stop()、suspend()、resume()
2. 编写两个线程:
第一个线程计算2-1000000之间的质数及个数
第二个线程计算1000000-2000000之间的质数及个数。
public class main
{
public static void main(String
[] args
)
{
MyThread1 mt1
= new MyThread1();
Mythread2 mt2
= new Mythread2();
mt1
.start();
mt2
.start();
}
}
class MyThread1 extends Thread
{
long count1
= 0;
boolean isPrime(long num
)
{
long tmp
= (long) Math
.sqrt(num
);
for (long i
= 2; i
<= tmp
; i
++)
{
if (num
% i
== 0)
{
return false;
}
}
return true;
}
public void run()
{
for (long i
= 2; i
<= 1000000; i
++)
{
if (isPrime(i
))
{
System
.out
.println("This is from thread 1: " + i
+ " is a prime!");
count1
++;
}
}
System
.out
.println("The number of primes in thread1 is: " + count1
);
}
}
class Mythread2 extends Thread
{
long count2
= 0;
boolean isPrime(long num
)
{
long tmp
= (long) Math
.sqrt(num
);
for (long i
= 2; i
<= tmp
; i
++)
{
if (num
% i
== 0)
{
return false;
}
}
return true;
}
public void run()
{
for (long i
= 1000000; i
<= 2000000; i
++)
{
if (isPrime(i
))
{
System
.out
.println("This is from thread 2: " + i
+ " is a prime!");
count2
++;
}
}
System
.out
.println("The number of primes in thread2 is: " + count2
);
}
}
转载请注明原文地址: https://lol.8miu.com/read-10181.html