1、编写一个有两个线程的程序,第一个线程用来计算2~100000之间的素数的个数,第二个线程用来计算100000~200000之间的素数的个数,最后输出结果。
package com.qiku.day23; public class Zuo01 { public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { int index = 0; @Override public void run() { for (int i = 2; i <=100000 ; i++) { boolean flag = true; for (int j = 2; j < i ; j++) { if (i%j==0){ flag = false; break; } } if (flag == true){ index++; } } System.out.println("2-100000的个数:"+index); } }); Thread t2 = new Thread(new Runnable() { int index = 0; @Override public void run() { for (int i = 100000; i <=200000 ; i++) { boolean flag = true; for (int j = 2; j < i ; j++) { if (i%j==0){ flag = false; break; } } if (flag == true){ index++; } } System.out.println("100000-200000的个数:"+index); } }); t1.start(); t2.start(); } }
2、模拟多线程并发问题,并解决(方式越多越好)
package com.qiku.day23; public class Zuo02 { private int beanNum; public Demo02(int beanNum) { this.beanNum = beanNum; } //拿豆子方法 public void catchBean(){ if (beanNum == 0){ throw new RuntimeException("没豆子了,,,"); } beanNum--; } public int getBeanNum() {return beanNum;} public void setBeanNum(int beanNum) {this.beanNum = beanNum;} public static void main(String[] args) { Demo02 demo02 = new Demo02(100); Thread t1 = new Thread(new Runnable() { @Override public void run() { while (true){ demo02.catchBean(); Thread.yield();//将线程的状态 由运行状态改为 就绪状态 继续等待分配时间片 System.out.println( Thread.currentThread().getName() + "豆子的数量"+demo02.getBeanNum()); } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { while (true){ demo02.catchBean(); Thread.yield(); System.out.println(Thread.currentThread().getName() + "豆子的数量"+demo02.getBeanNum()); } } }); t1.start(); t2.start(); } }