Java two threads alternately print odd and even numbers (comparison of two methods)

Introduction

This article will follow the article "Java multi-threaded wait() and notify() series method usage tutorial" , we will show the usage and advantages of the following wait()methods and methods through "two threads alternately print odd and even numbers within 100", of course notify()To reflect the advantages, it is natural to compare the code that does not use these two methods to achieve the same function. Through the explanations of these articles, you can thoroughly understand the wait()method and notify()the usage of the method.

1. Alternately print odd and even numbers only through the synchronized keyword

1. Implementation logic:

Create two threads, one thread is responsible for printing odd numbers, and the other thread is responsible for printing even numbers. The two threads compete for the same object lock. Each time a number is printed, the lock is released, and then another thread gets the lock and prints the next number.

2. Code implementation:

public class PrintOddEven1 {
	private static int count;

	private static final Object object = new Object();

	public static void main(String[] args) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (count < 100) {
					synchronized (object) {
						if ((count & 1) == 0) {
							System.out.println(Thread.currentThread().getName() + ":" + count++);
						}
					}
				}

			}
		}, "偶数线程").start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				while (count < 100) {
					synchronized (object) {
						if ((count & 1) == 1) {
							System.out.println(Thread.currentThread().getName() + ":" + count++);
						}
					}
				}

			}
		}, "奇数线程").start();
	}

}

3. Result output:

偶数线程:0
奇数线程:1
偶数线程:2
奇数线程:3
偶数线程:4
奇数线程:5
偶数线程:6
奇数线程:7
偶数线程:8
奇数线程:9
偶数线程:10

4. Result analysis:

By creating two threads, these two threads share the objectobject lock. When one thread finishes printing a number, it will release the object lock, and the other thread will get the object lock, and then judge whether it is an even number (odd number), and print if the conditions are met.

2. Alternately print odd and even numbers by using the synchronized keyword with the wait and notify methods

1. Implementation logic:

There is no need to judge whether the number is odd or even, the two threads alternately print the number by waiting for the wake-up mechanism.

2. Code implementation:

public class PrintOddEven2 {

	private static int count = 0;
	private static final Object object = new Object();

	public static void main(String[] args) {
		new Thread(new printer(), "偶数线程,").start();
		new Thread(new printer(), "奇数线程,").start();
	}

	static class printer implements Runnable {

		@Override
		public void run() {
			while (count <= 100) {
				synchronized (object) {
					// 打印数字,并立即释放锁
					System.out.println(Thread.currentThread().getName() + "打印:" + count++);
					object.notify();
					// 此处判断,是为了打印完了100个数字后,程序能够正常结束,否则程序将一直等待下去,耗费系统资源。
					if (count <= 100) {
						try {
							object.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

}


3. Result output:

偶数线程,打印:0
奇数线程,打印:1
偶数线程,打印:2
奇数线程,打印:3
偶数线程,打印:4
奇数线程,打印:5
偶数线程,打印:6
奇数线程,打印:7
偶数线程,打印:8
奇数线程,打印:9
偶数线程,打印:10
……省略

4. Result analysis:

In this way, the writing method is concise. After the thread gets the object lock, it immediately prints the number, and then notify()releases the lock and then calls wait()the method to make the thread enter the waiting state. After another thread gets the lock, it also prints the number immediately, then notify()releases the lock, and then enters the waiting state. Both threads can stop gracefully until all numbers up to 100 are printed.

Summarize

This article is an example tutorial on the usage of and methods, showing wait()the usage of and methods. The next article will show another use case of he and methods, "Consumer-Producer Pattern of Design Patterns", and will take you to continue to understand the use of the thread wake-up notification mechanism. where the meaning lies.notify()wait()notify()wait()notify()

Suggested collection:

For a series of tutorials about synchronized关键字, wait(), and notify()methods, please refer to the following articles:

"Two Ways and Principles of Synchronized Implementing Class Locks in Java"

"Two ways and principle analysis of synchronized implementation of object lock in Java"

"Java multi-threaded wait() and notify() series method usage tutorial"

"The use of notifyAll() method in Java multithreading tutorial"

"Analysis and Code Verification of Synchronized Reentrancy and Uninterruptibility in Java"

"Eight usage scenarios of Java multi-threaded access to Synchronized synchronization methods"

"Two Ways of Creating Threads in Java Official Documents and Analysis of Advantages and Disadvantages"

"Thread-safe and thread-unsafe analysis and examples in Java"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324156352&siteId=291194637