Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 13 Threads

Concurrent Access Problems

Concurrent programming in threads is fraught with pitfalls and problems. We will discuss two main concurrent access problems—data races and deadlocks—in this section.

Data Races

Threads share memory, and they can concurrently modify data. Since the modification can be done at the same time without safeguards, this can lead to unintuitive results.

When two or more threads are trying to access a variable and one of them wants to modify it, you get a problem known as a data race (also called as race condition or race hazard). Listing 13-9 shows an example of a data race.

Listing 13-9.  DataRace.java

 // This class exposes a publicly accessible counter

//to help demonstrate data race problem class Counter {

public static long count = 0;

}

//This class implements Runnable interface

//Its run method increments the counter three times class UseCounter implements Runnable {

public void increment() {

//increments the counter and prints the value

//of the counter shared between threads Counter.count++; System.out.print(Counter.count + " ");

}

public void run() { increment(); increment(); increment();

}

}

// This class creates three threads public class DataRace {

public static void main(String args[]) { UseCounter c = new UseCounter(); Thread t1 = new Thread(c);

Thread t2 = new Thread(c); Thread t3 = new Thread(c); t1.start();

t2.start();

t3.start();

}

}

In this program, there is a Counter class that has a static variable count. In the run() method of the UseCounter class, you increment the count three times by calling the increment() method. You create three threads in the main() function in the DataRace class and start it. You expect the program to print 1 to 9 sequentially as the threads run and

407

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]