import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CPU
{
static int num =Runtime.getRuntime().availableProcessors();
static CyclicBarrier k = new CyclicBarrier(num);
public static void main(String[] args) throws InterruptedException
{
for(int i=0;i<num;i++)
{
new Thread(new Run()).start();
}
}
static class Run implements Runnable
{
public void run()
{
int busyTime = 10;
int idleTime = busyTime;
try
{
k.await();
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
catch (BrokenBarrierException e1)
{
e1.printStackTrace();
}
while(true){
long startTime = System.currentTimeMillis();
while((System.currentTimeMillis()-startTime)<=busyTime);
try
{
Thread.sleep(idleTime);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
The result is as follows:
From the figure, we can see that our CPU occupation rate is generally stable at about 50%. Later fluctuations were caused by my opening of QQ to take screenshots.
2: The second program: This program is the same as the first program principle. The only difference is to make the occupation rate distributed as a sine. Therefore A sampling point, that is, the 300ms is cut by business and idle, and its proportion is the value of the sampling point. The program is as follows:
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CUP_SINA
{
static int num =Runtime.getRuntime().availableProcessors();
static CyclicBarrier k = new CyclicBarrier(num);
public static void main(String[] args) throws InterruptedException
{
for(int i=0;i<num;i++)
{
new Thread(new Run()).start();
}
}
static class Run implements Runnable
{
public void run()
{
final int SAMPLING_COUNT = 200;
final double PI = 3.1415926535;
final int TOTAL_AMPLITUDE = 300;
long startTime = 0;
int[] busySpan = new int[SAMPLING_COUNT];
int amplitude = TOTAL_AMPLITUDE/2;
double radian = 0.0;
double radianIncrement = 2.0/(double)SAMPLING_COUNT;
for(int i=0;i<SAMPLING_COUNT;i++)
{
busySpan[i] = (int)(amplitude+Math.sin(PI*radian)*amplitude);
radian += radianIncrement;
}
for(int j=0;;j=(j+1) % SAMPLING_COUNT)
{
try
{
k.await();
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
catch (BrokenBarrierException e1)
{
e1.printStackTrace();
}
startTime = System.currentTimeMillis();
while((System.currentTimeMillis()-startTime)<=busySpan[j]);
try
{
Thread.sleep(TOTAL_AMPLITUDE-busySpan[j]);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
The result is as follows:
can be seen from the figure that its CPU share presents a sine distribution, and the subsequent fluctuations are caused by opening QQ screenshots.