Communication notes between threads
-
Work on thread A and then thread B
Idea: To use an object lock, A first occupies the object lock, and then releases it to B after use
public class Test { private static Object lock = new Object(); static class ThreadA implements Runnable { @Override public void run() { synchronized (lock) { for (int i = 0; i < 100; i++) { System.out.println("Thread A " + i); } } } } static class ThreadB implements Runnable { @Override public void run() { synchronized (lock) { for (int i = 0; i < 100; i++) { System.out.println("Thread B " + i); } } } } public static void main(String[] args) throws InterruptedException { new Thread(new ThreadA()).start(); new Thread(new ThreadB()).start(); } }
-
A thread prints even numbers, B thread prints odd numbers
Idea: Use volatile+synchronized, because a++ is not an atomic operation, it needs to be locked
public class Test { private static Object lock = new Object(); private static volatile int a = 0; static class ThreadA implements Runnable { @Override public void run() { while(a<100){ if(a%2==1){ try { System.out.println("ThreadA: " + a); synchronized (lock){ a++; } } catch (Exception e) { e.printStackTrace(); } } } } } static class ThreadB implements Runnable { @Override public void run() { while(a<100){ if(a%2==0){ try { System.out.println("ThreadB: " + a); synchronized (lock){ a++; } } catch (Exception e) { e.printStackTrace(); } } } } } public static void main(String[] args) { new Thread(new ThreadA()).start(); new Thread(new ThreadB()).start(); } }