美文网首页
老师布置的奇葩作业五

老师布置的奇葩作业五

作者: 乱世佳人i | 来源:发表于2016-08-30 11:28 被阅读0次

    package practice5;

    /**

    * 5、制作两个线程对象,要求用同步块的方式使第一个线程运行2次,

    * 然后将自己阻塞起来,唤醒第二个线程,第二个线程再运行2次,

    * 然后将自己阻塞起来,唤醒第一个线程 ,两 个线程交替执行。

    * @author Administrator

    *

    */

    public class Test {

    public static void main(String[] args) {

    ThreadA t = new ThreadA();

    Thread t1 = new Thread(t);

    Thread t2 = new Thread(t);

    t1.setName("线程一");

    t2.setName("线程二");

    t1.start();

    t2.start();

    }

    }

    class ThreadA implements Runnable {

    int num = 1;

    public void run() {

    while (true) {

    synchronized (this) {

    notify();

    if (num >0) {

    try {

    Thread.currentThread().sleep(10);

    } catch (InterruptedException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    System.out.println(Thread.currentThread().getName() + "\t运行第一次 " );

    num++;

    } else {

    break;

    }

    if (num > 0) {

    try {

    Thread.currentThread().sleep(10);

    } catch (InterruptedException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    System.out.println(Thread.currentThread().getName() + "\t运行第二次" );

    num++;

    } else {

    break;

    }

    try {

    wait();

    } catch (InterruptedException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    }

    }

    }

    }

    相关文章

      网友评论

          本文标题:老师布置的奇葩作业五

          本文链接:https://www.haomeiwen.com/subject/htvfettx.html