here is my class
public class ThreadTest {
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
threadTest.m1();
synchronized (threadTest) {
threadTest.m2();
}
System.out.println("End of main thread");
}
public void m1() {
Thread myThread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
System.out.println("end of mythread");
}
});
myThread.start();
}
public void m2() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
Although i put my code inside synchronized
block it doesn't seem to work properly and both of for
loops are run parallelly.How can i run those loops as threadsafe in multi-threaded environment with a synchronized block.Where is the mistake i made my code given?
thanks!