1、编写一个有两个线程的程序,第一个线程用来计算2~100000之间的素数的个数,第二个线程用来计算100000~200000之间的素数的个数,最后输出结果。
public class Demo01 {
public static void main(String[] args) {
Thread thread = new Thread(){
@Override
public void run() {
boolean flag = true;
int index=0;
for (int i = 2; i <=100000 ; i++) {
for (int j = 2; j <Math.sqrt(i) ; j++) {
if(i%j==0){
flag=false;
break;
}else {
flag=true;
}
}
if(flag){
index++;
}
}
System.out.println("thread素数的个数为:"+index);
}
};
Thread thread2 = new Thread(){
@Override
public void run() {
boolean flag = true;
int index=0;
for (int i = 100000; i <=200000 ; i++) {
for (int j = 2; j <Math.sqrt(i) ; j++) {
if(i%j==0){
flag=false;
break;
}else {
flag=true;
}
}
if(flag){
index++;
}
}
System.out.println("thread2素数的个数为:"+index);
}
};
thread.start();
thread2.start();
}
}
2、模拟多线程并发问题,并解决(方式越多越好)
模拟两个人(两个线程),同时在桌子上拿豆子,考虑并发出错情况
public class Demo02 {
public static void main(String[] args) {
dd d1 = new dd(100);
Thread t1 = new Thread(){
@Override
public void run() {
while (true){
try {
d1.getDD();
System.out.println(Thread.currentThread().getName()+":"+
d1.getNum());
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
Thread t2 = new Thread(){
@Override
public void run() {
while (true){
try {
d1.getDD();
System.out.println(Thread.currentThread().getName()+":"+
d1.getNum());
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
t1.start();
t2.start();
}
}
class dd{
private int num;
public dd(int num) {
this.num = num;
}
public void getDD() throws Exception {
if(num==0){
throw new Exception("没豆子了");
}
else num--;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}