This example shares the specific code for Java to implement multi-threaded alternating printing of two numbers for your reference. The specific content is as follows
Method 1, use wait and notify
package ; public class T01 { public static void main(String[] args) { char[] char1 = "AAAAAA".toCharArray(); char[] char2 = "BBBBBB".toCharArray(); Object object = new Object(); Thread thread1 = new Thread(() -> { synchronized(object){// When using notify and wait, you must select to obtain the lock for (int i = 0; i < ; i++) { try { (char1[i]); (); (); } catch (InterruptedException e) { (); } } ();//It must be added, otherwise the program cannot end, and one of the two threads will always have a wait state at the end, so it must be added here } },"t1"); Thread thread2 = new Thread( () -> { synchronized(object){ for (int i = 0; i < ; i++) { try { (char2[i]); (); (); } catch (InterruptedException e) { (); } } (); } },"t2"); (); (); } }
Method 2, use the LockSupport method
package ; import ; public class T02 { static Thread thread1 ; static Thread thread2 ; public static void main(String[] args) { char[] char1 = "AAAAAA".toCharArray(); char[] char2 = "BBBBBB".toCharArray(); thread1 = new Thread(() -> { for (int i = 0; i < ; i++) { (char1[i]); (thread2); (); } },"t1"); thread2 = new Thread(() -> { for (int i = 0; i < ; i++) { (); (char2[i]); (thread1); } },"t2"); (); (); } }
Method 3, use CAS spin lock
package ; public class T03 { enum ReadEnum{ T1, T2; } static volatile ReadEnum r = ReadEnum.T1; public static void main(String[] args) { char[] char1 = "AAAAAA".toCharArray(); char[] char2 = "BBBBBB".toCharArray(); Thread thread1 = new Thread(() ->{ for (int i = 0; i < ; i++) { while (r != ReadEnum.T1) { } (char1[i]); r = ReadEnum.T2; } },"t1"); Thread thread2 = new Thread(() ->{ for (int i = 0; i < ; i++) { while (r != ReadEnum.T2) { } (char2[i]); r = ReadEnum.T1; } },"t2"); (); (); } }
Method 4, use the Condition method
package ; import ; import ; public class T04 { public static void main(String[] args) { char[] char1 = "AAAAAA".toCharArray(); char[] char2 = "BBBBBB".toCharArray(); ReentrantLock lock = new ReentrantLock(); Condition condition1 = (); Condition condition2 = (); Thread thread1 = new Thread(() ->{ try { (); for (int i = 0; i < ; i++) { (char1[i]); ();//Wake up thread 2 execution ();//Thread 1 is waiting } (); }catch (Exception e) { (); }finally{ (); } },"t1"); Thread thread2 = new Thread(() ->{ try { (); for (int i = 0; i < ; i++) { (char2[i]); (); (); } (); } catch (Exception e) { (); }finally{ (); } },"t2"); (); (); } }
The advantage of Condition compared to notify is that Condition can specify the thread that needs to be woken up, while notify cannot be specified. You can only randomly wake up one or all (notifyAll)
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.