Recently I am maintaining a Java project, and in the group we are chatting about the pros and cons of Java! Unfortunately, some ultimate fans of Java always claim that performance is no longer as bad as C++, and many standard libraries are written by masters, how stable they are, etc. I simply studied it carefully, and one of the instructions they gave me was that to deliver messages between threads, it is enough to use BlockingQueue, which has been encapsulated in java.
Since it is enough, let’s write code to test it. Simply write a small program and do some testing:
import base.MyRunnable;
public class Test
{
public static void main(String[] args)
{
BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>();
java.lang.Runnable r = new MyRunnable(queue);
Thread t = new Thread(r);
t.start();
while(true)
{
try
{
while(true)
{
for(int i =0;i < 10000;i++)
{
queue.offer(i);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
//Packages that need to be added
package base;
import java.lang.Runnable;
import java.util.concurrent.*;
import java.util.*;
public class MyRunnable implements Runnable
{
public MyRunnable(BlockingQueue<Integer> queue)
{
this.queue = queue;
}
public void run()
{
Date d = new Date();
long starttime = d.getTime();
System.err.println(starttime);
int count = 0;
while(true)
{
try
{
Integer i = this.queue.poll();
if(i != null)
{
count++;
}
if(count == 100000)
{
Date e = new Date();
long endtime = e.getTime();
System.err.println(count);
System.err.println(endtime);
System.err.print(endtime - starttime);
break;
}
}
catch (Exception e)
{
}
}
}
private BlockingQueue<Integer> queue;
}
I used offer and poll in the above test code. Let’s take a look at these two implementation functions. The first is offer