两个线程一个打印1,一个打印2,要求循环打印1212121212

两个线程一个打印1,一个打印2,要求循环打印121212

方法1:

分析问题

两个线程,可以想到的是多线程编程,共享变量,数据等,设想先让一个线程打印1,然后处于等待(wait)状态,接着另一个线程打印2,然后唤醒(notify)线程1,线程2再进入等待(wait)状态,线程1被唤醒后接着打印1,依次循环输出即可

代码

public class Test {
    static final Object object = new Object();
    public static void main(String[] args){
        //线程1
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0;i<5;i++){
                    synchronized (object){
                        System.out.println("1");
                        object.notify(); //唤醒线程2
                        try {
                            object.wait();//线程1进入等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
        //线程2
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0;i<5;i++){
                    synchronized (object){
                        System.out.println("2");
                        object.notify();//唤醒线程1
                        try {
                            object.wait();//线程2进入等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
  

结果:

1
2
1
2
1
2
1
2
1

2

方法2:

分析问题:

使用volatile保证数据的可见性,避免多线程访问同一个变量,它的值刷新不及时的问题;设想定义一个volatile修饰的boolean变量flag,当flag为true时,线程1打印1,同时修改flag的值,置为false,当flag为false时,线程2打印2,同时修改falg的值,置为true,依次循环即可

代码

public class Test {
    volatile static boolean flag = true;
    public static void main(String[] args){
        Thread t1 = new MyThread(1);
        Thread t2 = new MyThread(2);
        t1.start();
        t2.start();
    }

    static class MyThread extends Thread{
        int printValue;
        public MyThread(int printValue){
            this.printValue = printValue;
        }
        @Override
        public void run() {
            for(int i = 0;i<5;i++){
                if(flag){
                    System.out.println("1");
                }else{
                    System.out.println("2");
                }
                flag = !flag;
            }
        }
    }
} 

结果:

1
2
1
2
1
2
1
2
1
2

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值