Start with the question of buying a ticket
package com.google.thread; /** * Security issues under the example of buying a ticket. * Reason for appearing * * Solutions * * Synchronized code blocks. * * Restrooms on the train. */ class Ticker implements Runnable{ public int num = 100; Object obj = new Object(); public void run() { while ( true ) { // synchronized code block if (num > 0 ) { try { Thread.sleep(10); System.out.println(Thread.currentThread().getName() + "...." + num--); } catch (InterruptedException e) { e.printStackTrace (); } } } } } /* Thread safety issues. Ticket 0 will be sold. Thread-3....-1 Thread-1....2 Thread-2....0 */ public class ThreadDemo extends Thread { public static void main(String[] args) { Ticker t = new Ticker(); Thread t1 = new Thread(t); // Create a thread Thread t2= new Thread(t); Thread t3=new Thread(t); Thread t4=new Thread(t); t1.start(); // Start thread t2.start(); t3.start(); t4.start(); } }
Thread safety issues.
Ticket 0 will be sold.
Multiple threads are manipulating shared data.
There are multiple threads of code that operate on shared data.
When a thread is executing multiple pieces of code that operate on shared data, other threads participate in the operation. This can lead to thread safety issues.
Solution