package com.qiku.day23; public class Zy01 { public static void main(String[] args) throws InterruptedException { // 1、编写一个有两个线程的程序,第一个线程用来计算2~100000之间的素数的个数,第二个线程用来计算100000~200000之间的素数的个数,最后输出结果。 Thread t1 = new Thread() { @Override
public void run() {
synchronized (ThreadTest01.class) {
boolean b1;
for (int i = 2; i <= 100000; i++) {
b1 = true;
for (int j = 2; j < i / 2 + 1; j++) {
if (i % j == 0) {
b1 = false;
break;
}
}
if (b1) {
index++;
}
}
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
synchronized (ThreadTest01.class) {
boolean b2;
for (int i = 100000; i <= 200000; i++) {
b2 = true;
for (int j = 2; j < i / 2 + 1; j++) {
if (i % j == 0) {
b2 = false;
break;
}
}
if (b2) {
index++;
}
}
}
}
};
t1.setDaemon(true);//设置t1 为守护线程 t1.start(); t2.start(); t1.join(); t2.join(); // System.out.println("t1"+t1.isDaemon()); // System.out.println("t2"+t2.isDaemon()); } }
package com.qiku.yrc.work23;
public class Table01 {
private int num;
public void catchBean() {
if (num == 0){//抢完了
throw new RuntimeException("豆子没了");
}
int n = num;
n = n - 1;
Thread.yield();
num = n;
}
@Override
public String toString() {
return "Table01{" +
"num=" + num +
'}';
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public Table01() {
}
public Table01(int num) {
this.num = num;
}
public static void main(String[] args) {
// 2、模拟多线程并发问题,并解决(方式越多越好)
//
// 模拟两个人(两个线程),同时在桌子上拿豆子,考虑并发出错情况
}
}
package com.qiku.yrc.work23;
public class Table01Test {
public static void main(String[] args) {
Table01 t1 = new Table01(888);
Thread thread1 = new Thread("线程一") {
@Override
public void run() {
super.run();
while (true) {
t1.catchBean();
Thread.yield();
System.out.println(Thread.currentThread().getName()+" "+t1.getNum());
}
}
};
Thread thread2 = new Thread("线程二") {
@Override
public void run() {
super.run();
while (true) {
t1.catchBean();
Thread.yield();
System.out.println(Thread.currentThread().getName()+" "+t1.getNum());
}
}
};
thread1.start();
thread2.start();
}
}