多线程

来源:互联网 发布:vivox7和荣耀8知乎 编辑:程序博客网 时间:2024/06/05 20:29

作业1:

 编写多线程程序,模拟多个人通过一个山洞。这个山洞每次只能通过一个人,每个人通过山洞的时间为2秒(sleep)。随机生成10个人,都要通过此山洞,用随机值对应的字符串表示人名,打印输出每次通过山洞的人名。提示:利用线程同步机制,过山洞用一条输出语句表示,该输出语句打印输出当前过山洞的人名,每个人过山洞对应一个线程,哪个线程执行这条输出语句,就表示哪个人过山洞。

程序代码:

package thread;public class Test1 {    public static void main(String[] args) {        Shandong shandong = new Shandong();        new Thread(shandong, "1").start();        new Thread(shandong, "2").start();        new Thread(shandong, "3").start();        new Thread(shandong, "4").start();        new Thread(shandong, "5").start();        new Thread(shandong, "6").start();        new Thread(shandong, "7").start();        new Thread(shandong, "8").start();        new Thread(shandong, "9").start();        new Thread(shandong, "10").start();    }}class Shandong extends Thread{    public void run() {        synchronized(this){            System.out.println(Thread.currentThread().getName()+"正在通过,请等待2s");            try {                sleep(2000);            } catch (InterruptedException e) {                e.printStackTrace();            }        }}}

运行结果:



作业2:

   用两个线程玩猜数字游戏,第一个线程负责随机给出1~100之间的一个整数,第二个线程负责猜出这个数。要求每当第二个线程给出自己的猜测后,第一个线程都会提示“猜小了”、“猜大了”或“猜对了”。猜数之前,要求第二个线程要等待第一个线程设置好要猜测的数。第一个线程设置好猜测数之后,两个线程还要相互等待,其原则是:第二个线程给出自己的猜测后,等待第一个线程给出的提示;第一个线程给出提示后,等待给第二个线程给出猜测,如此进行,直到第二个线程给出正确的猜测后,两个线程进入死亡状态。


实现代码:

package thread;import java.util.Random;public class Test {public static void main(String[] args){Number num =new Number();Thread   t =new Thread(num);t.run();try {Thread.sleep(10);Number num2 =new Number ();Thread t1 =new Thread(num2);while(true) {t1.interrupt();t1.run();Thread.sleep(10);t.interrupt();if(num2.getNum()==num.getNum()){System.out.println("猜的数字为:"+num2.getNum()+"猜对了");break;}else if(num2.getNum()<num.getNum())System.out.println("猜的数字为:"+num2.getNum()+"猜小了");elseSystem.out.println("猜的数字为:"+num2.getNum()+"猜大了");}}catch(InterruptedException e) { e.printStackTrace();}}}class Number implements Runnable{int num;public synchronized void run() {Random n =new Random();num=n.nextInt(100); } public int getNum() { return num; } public void setNum(int num) { this.num=num; }}


运行结果:



原创粉丝点击