算法

Java实现两个线程交替打印1-100

2018-05-17  本文已影响1212人  chris_irving

这道java基础题主要考察的是对java并发基础知识的掌握,一般需要掌握多线程中的wait(),notify(),notifyAll(),join(),yield(),sleep()等方法的灵活使用。

class TestThread implements Runnable {
    int i = 1;
    @Override
    public void run() {
        while (true) {
            /*指代的为TestThread,因为使用的是implements方式。若使用继承Thread类的方式,慎用this*/
            synchronized (this) {
                /*唤醒另外一个线程,注意是this的方法,而不是Thread*/
                notify();
                try {
                    /*使其休眠100毫秒,放大线程差异*/
                    Thread.currentThread();
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (i <= 100) {
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                    i++;
                    try {
                        /*放弃资源,等待*/
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

创建main函数

public static void main(String[] args) {
        /*只有一个TestThread对象*/
        TestThread t = new TestThread();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);

        t1.setName("线程1");
        t2.setName("线程2");

        t1.start();
        t2.start();
    }

执行结果如下:

线程1:1
线程2:2
线程1:3
线程2:4
线程1:5
线程2:6
...
线程2:90
线程1:91
线程2:92
线程1:93
线程2:94
线程1:95
线程2:96
线程1:97
线程2:98
线程1:99
线程2:100

注意 以上是在IDEA及Eclipse环境下的mian()方法下执行结果,在笔者Android Studio中的单元测试中(@Test方法下)执行未打印任何信息

上一篇下一篇

猜你喜欢

热点阅读