I have attached the question that I am answering for not thread safe class. The output changes after multiple runs
This is my code for testing if a class is not thread safe.
public class AddThread implements Runnable {
private CardDeck seq;
private int input;
public AddThread(int input, CardDeck deck){
this.input =input;
this.seq=deck;
}
public void run() {
for (int i=0;i<input;i++){
seq.dealCard();
}
}
public class SimpleThreads {
public static void main(String[] args) throws InterruptedException{
CardDeck deck = new CardDeck();
AddThread t1 = new AddThread(20000, deck);
AddThread t2 = new AddThread(40000, deck);
Thread Th1 = new Thread(t1);
Thread Th2 = new Thread(t2);
Th1.start();
Th2.start();
Th1.join();
Th2.join();
System.out.println(deck.sequenceNumber);
}
}
public class UnSafeSequence {
private int value = 0;
public int[] sequenceNumber;
public int dealCard(){
return value++;
}
public int getResult(){
return value;
}
}