package com.codegym.task.task17.task1701;
import java.util.ArrayList;
import java.util.List;
/*
Notes
*/
public class Solution {
public static void main(String[] args) {
new NoteThread().start();
new NoteThread().start();
}
public static class Note {
public static final List<String> notes = new ArrayList<>();
public static void addNote(String note) {
notes.add(0, note);
}
public static void removeNote(String threadName) {
String note = notes.remove(0);
if (note == null) {
System.out.println("Another thread deleted our note");
} else if (!note.startsWith(threadName)) {
System.out.println("Thread [" + threadName + "] deleted someone else's note [" + note + "]");
} else {
System.out.println("Thread [" + threadName + "] deleted its own note [" + note + "]");
}
}
}
public static class NoteThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
Note.addNote ( getName () + "-Note" + i );
try{
Thread.sleep ( 1 );
}catch (InterruptedException o){
}
}
for(int i = 0 ; i < 1000;i++) {
Note.removeNote ( this.getName () );
}
}
}
}
Can somebody explain why the code doesnt work when i use "Thread.currentThread.getName()" as a parameter for removeNote methon .
Under discussion
Comments (1)
- Popular
- New
- Old
You must be signed in to leave a comment
KIN SOCHEAT
9 October 2019, 00:30
you use too much loop in run()
the result should be:
Thread [Thread-0] deleted someone else's note [Thread-1-Note0]
Thread [Thread-1] deleted someone else's note [Thread-0-Note0]
Thread [Thread-0] deleted someone else's note [Thread-1-Note1]
Thread [Thread-1] deleted its own note [Thread-1-Note1]
Thread [Thread-1] deleted its own note [Thread-1-Note2]
0