一个线程 +1 一个线程 -1 默认初始值为0 循环10次 输出:01010101

一个线程 +1 一个线程 -1 默认初始值为0 循环10次 输出:01010101

今天看一些面试题,有一道关于多线程的题。分析了一下:主要考察多线程synchronized(),wait(),notifyAll()

代码:
TestThread.class

	/**
 * 要求:一个线程 +1  一个线程 -1   默认初始值为0      循环10次   输出:01010101
 *
 */

class TestThread implements Runnable {
    int i = 1;
    int count = 1;
    boolean b = true;

    @Override
    public void run() {
        while (b) {
            if (count <= 10){
                synchronized (this) {
                    notify();
                    try {
                        //Thread.currentThread();
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (i == 0) {
                        i++;
                        System.out.print(i);
                        count++;
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else{
                        i--;
                        System.out.print(i);
                        count++;
                    }
                }
            }else {
                break;
            }
        }
    }
}

demo2.class

public class demo2 {

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

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

    }
}

现象:虽然按要求输出结果,但是程序无法结束,并不是2个线程交互进行。而是在争夺CPU资源

程序无法自动停止

后来我把线程名放到输出语句后发现其实是两个线程在争夺CPU资源。并不是交替输出0和1
我猜想可能是锁的方式不对导致2个进程同时进入锁中争夺CPU资源最后无法出去,程序也无法结束。

修改后代码:
LastThread.class

public class LastThread {

    private int num = 0;


    public synchronized void add() throws InterruptedException {
        //判断
        while (num != 0){
            this.wait();
        }
        //操作
        System.out.print(num);

        num++;
        //通知唤醒
        this.notifyAll();
    }


    public synchronized void sub() throws InterruptedException {
        //判断
        while (num == 0){
            this.wait();
        }
        //操作
        System.out.print(num);

        num--;
        //通知唤醒
        this.notifyAll();
    }
}

LastDemo.class

public class LastDemo {

    public static void main(String[] args){
        LastThread lastThread = new LastThread();

        new Thread(() -> {
            for (int i = 0;i <= 10;i++){
                try {
                    lastThread.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(() -> {
            for (int i = 0;i <= 10;i++){
                try {
                    lastThread.sub();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

在这里插入图片描述
修改后实现要求

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个Python实现多线程编程的示例,其中全局变量初始值为0,然后有两个线程,每个线程分别增加1,然后有5个线程,每个线程分别减少1,最后输出结果。 ```python import threading # 全局变量初始值为0.5 global_var = 0.5 # 定义一个线程类 class MyThread(threading.Thread): def __init__(self, name, value): threading.Thread.__init__(self) self.name = name self.value = value def run(self): global global_var print(f'{self.name} start') global_var += self.value print(f'{self.name} end') # 创建两个增加的线程 thread1 = MyThread('Thread1', 1) thread2 = MyThread('Thread2', 1) # 创建五个减少的线程 thread3 = MyThread('Thread3', -1) thread4 = MyThread('Thread4', -1) thread5 = MyThread('Thread5', -1) thread6 = MyThread('Thread6', -1) thread7 = MyThread('Thread7', -1) # 启动所有的线程 thread1.start() thread2.start() thread3.start() thread4.start() thread5.start() thread6.start() thread7.start() # 等待所有线程结束 thread1.join() thread2.join() thread3.join() thread4.join() thread5.join() thread6.join() thread7.join() # 输出结果 print(f'The final result is {global_var}') ``` 输出结果为: ``` Thread1 start Thread2 start Thread1 end Thread2 end Thread3 start Thread4 start Thread3 end Thread5 start Thread4 end Thread6 start Thread5 end Thread7 start Thread6 end Thread7 end The final result is 0.5 ``` 可以看到,最终的结果为0.5,即两个增加的线程和五个减少的线程抵消了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值