使用内置信号量在Java中实现锁定

时间:2017-05-06 03:11:41

标签: java multithreading semaphore java-threads locks

我创建了5个线程,并且都访问了关键部分并从文件中读取值并更改了值。但最终所有打印的值都相同,即第一个值。如何使用信号量实现锁定,以便一次只有一个线程访问临界区?

#include <iostream>

int walls,rooms,total_walls; //It only makes sense if all of these are integers.
//These are global declarations, they can be modified by any function in the program

void input_walls() { 
    /* Functions are notated as so in C++: 
       {return type} {function_name}({input},{input},...)
       It's pointless to annotate functions that don't return anything
       with a declaration of a float return type (they'll just return 0 */
    std::cin >> walls;
    while(walls < 0) {
        std::cout << "Please input a positive amount of walls per room.";
        std::cin >> walls;
    }
}

void input_rooms() {
    std::cin >> rooms;
    while(rooms < 0) {
         std::cout << "Please input a positive amount of rooms";
         std::cin >> rooms;
    }
}

void calculate_result() {
    total_walls = walls*rooms;
}

void output_result() {
    std::cout << "I'll need to paint " << total_walls << " walls!" << std::endl;
}

int main() {
    input_walls();
    input_rooms();
    calculate_result();
    output_result();
}

0 个答案:

没有答案