《编程之美》(Java实现) :让CPU占用率画直线和正弦曲线(Java实现)
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
?
?
package cglib;
?
public class jiekou {
??? public static void drawLine(){?? ?
??????? int usage = 700; ?
??????? System.out.println("Test Begins...");??????? ?
??????? while(true){???????? ?
??????????? long start = System.currentTimeMillis(); ?
??????????? while(System.currentTimeMillis() - start < usage ); ?
??????????? try{ ?
??????????????? Thread.sleep(1000-usage); ?
??????????? }catch(Exception e){ ?
??????????????? System.out.print(e); ?
??????????? }??????? ?
??????? } ?
??? } ?
??? public static void drawSin(){ ?
??????? double x = Math.PI / 2;? ?
??????? while(true){ ?
??????????? //下面這一句+1是因?yàn)閟inx可能為負(fù)數(shù),最大為-1,加上1的話就保證為正了 ?
??????????? //*0.5是應(yīng)為加1之后,最大數(shù)可能達(dá)到2,為了限制在1以內(nèi),所以*0.5 ?
??????????? long usage = (long)((Math.sin(x)+1)*0.5*1000); ?
??????????? System.out.println(usage); ?
??????????? long start =? System.currentTimeMillis(); ?
??????????? while(System.currentTimeMillis() - start < usage); ?
??????????? try{ ?
??????????????? Thread.sleep(1000 - usage); ?
??????????? }catch(Exception e){ ?
??????????????? System.out.print(e); ?
??????????? } ?
??????????? x += 0.1; ?
??????? } ?
??? }??? ?
??? public static void drawSinSpeedup(){ ?
??????? double x = Math.PI / 2;? ?
??????? //加入了刷新時(shí)間,可以調(diào)控曲線彎曲程度 ?
??????? int flushtime = 5000; ?
??????? while(true){ ?
??????????? long usage = (long)((Math.sin(x)+1)*0.5*flushtime); ?
??????????? System.out.println(usage); ?
??????????? long start =? System.currentTimeMillis(); ?
??????????? while(System.currentTimeMillis() - start < usage); ?
??????????? try{ ?
??????????????? Thread.sleep(flushtime - usage); ?
??????????? }catch(Exception e){ ?
??????????????? System.out.print(e); ?
??????????? } ?
??????????? x += 0.1; ?
??????? } ?
??? } ?
?? ?
??? public static void main(String[] args) throws InterruptedException { ?
?? ??? ?drawLine(); ?
?? ??? ?drawSin(); ?
??? } ?
??? }
轉(zhuǎn)載于:https://my.oschina.net/u/2822116/blog/723882
總結(jié)
以上是生活随笔為你收集整理的《编程之美》(Java实现) :让CPU占用率画直线和正弦曲线(Java实现)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: mysql字段timestamp为空映射
- 下一篇: sql随笔