猿问

线程同步,synhronized,锁

要求主线程执行100次,子线程执行10次,主线程执行100次,子线程执行10次。。。循环

代码如下:

public class Test_02 {


public static void main(String[] args){

    

    MeThread me = new MeThread();

    Thread t = new Thread(me);

    t.start();


    boolean flag = true;

    int i = 1;

    synchronized (me) {

        

        while (flag) {

            System.out.println(Thread.currentThread().getName() + i);

            i++;

            if (i % 100 == 0) {

                try {

                    Thread.currentThread().wait();

                } catch (InterruptedException e) {

                    

                    e.printStackTrace();

                }finally {

                    System.out.println("===========");

                    me.notify();//Thread.currentThread().notifyAll();也不行

                }

            }

        }

    }

}

}


class MeThread implements Runnable {

@Override

public synchronized void run() {

int i = 0;


    boolean flag = true;

    while (flag) {

        System.out.println(Thread.currentThread().getName() + i);

        i++;

        if (i % 10 == 0) {

            try {

                Thread.currentThread().wait();

            } catch (InterruptedException e) {

                

                e.printStackTrace();

            }finally {

                System.out.println("===========");

                

                this.notify();//Thread.currentThread().notifyAll();也不行

            }

        }

    }

}

}


慕容708150
浏览 527回答 2
2回答

蓝山帝景

public class Test_02 {public static void main(String[] args) {    MeThread me = new MeThread();    Thread t = new Thread(me);    t.start();    boolean flag = true;    //修改了初始值    int i = 0;    synchronized (me) {        while (flag) {            System.out.println(Thread.currentThread().getName() + i);            i++;            if (i % 100 == 0) {                try {                    //方便观察效果,睡眠1s                    Thread.sleep(1000);                    System.out.println("main===========");                    //从finally代码块中前移到wait()方法前                    me.notify();                    //锁对象为me                    me.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }    }}}class MeThread implements Runnable {@Overridepublic synchronized void run() {int i = 0;    boolean flag = true;    while (flag) {        System.out.println(Thread.currentThread().getName() + i);        i++;        if (i % 10 == 0) {            try {                //方便观察                Thread.sleep(1000);                System.out.println("MeThread===========");                //同步方法锁对象为this,notify()移动到wait()方法前                this.notify();                //同步方法锁对象为this                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }         }    }}}

炎炎设计

平时项目开发的时候这个多线程用在哪里?怎么使用?
随时随地看视频慕课网APP

相关分类

Java
我要回答