线程的简单应用
1、两个线程的计算
一个线程用来计算2~100000之间的素数的个数,另一个线程用来计算100000~200000之间的素数的个数,最后输出结果。
//实现接口方式
public class ThreadDw01 implements Runnable {
private int min;
private int max;
private int index;
boolean b;
public ThreadDw01() {
}
public ThreadDw01(int min, int max) {
this.min = min;
this.max = max;
}
@Override
public synchronized void run() {
for (int i = min; i <= max; i++) {
b = true;
for (int j = 2; j < i / 2 + 1; j++) {
if (i % j == 0) {
b = false;
break;
}
}
if (b) {
index++;
}
}
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
//测试类
public class ThreadTest01 {
// static int index = 0;//存放素数个数 匿名内部类使用
public static void main(String[] args) throws InterruptedException {
//实现接口方式
ThreadDw01 td1 = new ThreadDw01(2, 100000);
Thread t1 = new Thread(td1, "t1");
ThreadDw01 td2 = new ThreadDw01(100000, 200000);
Thread t2 = new Thread(td2, "t2");
//匿名内部类方式
// 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.start();
t2.start();
//main线程等待t1 t2结束再执行后续操作
t1.join();
t2.join();
// System.out.println("2~200000之间的素数个数:" + index);//匿名内部类使用
System.out.println("2~200000之间的素数个数:"+
(td1.getIndex() + td2.getIndex()));//实现接口使用
}
}
2、模拟多线程并发问题,并解决
模拟两个人(两个线程),同时在桌子上拿豆子,考虑并发出错情况
//抢豆子类
public class ThreadDw02 {
private int num;
public ThreadDw02(int num) {
this.num = num;
}
public void numSub() {
if (num == 0) {
throw new RuntimeException("豆子没有了!!!");
} else {
num--;
}
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
//测试类
public class ThreadTest02 {
public static void main(String[] args) throws InterruptedException {
ThreadDw02 td = new ThreadDw02(1000);
Thread t1 = new Thread() {
@Override
public void run() {
while (true) {
td.numSub();
Thread.yield();
System.out.println(Thread.currentThread().getName() + ":" + td.getNum());
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
while (true) {
td.numSub();
Thread.yield();
System.out.println(Thread.currentThread().getName() + ":" + td.getNum());
}
}
};
t1.start();
t2.start();
}
}