模擬搶票:
創(chuàng)新互聯(lián)主營欽州網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,app軟件開發(fā)公司,欽州h5小程序開發(fā)搭建,欽州網(wǎng)站營銷推廣歡迎欽州等地區(qū)企業(yè)咨詢
public class ThreadDownload implements Runnable {
private int num=99;
public void run()
{
while(true)
{
if(num<0)
{
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //模擬延遲,停止200毫秒
System.out.println(Thread.currentThread().getName()+"-"+num--);
}
}
public static void main(String[]args)
{ //一份資源
ThreadDownload web=new ThreadDownload();
System.out.println(Thread.currentThread().getName());//在main線程中,打印main
//多個代理
new Thread(web,"a").start();
new Thread(web,"b").start();
new Thread(web,"c").start();
}
}
模擬龜兔賽跑:
public class ThreadDownload implements Runnable {
private String winner;
public void run()
{
for(int step=1;step<=100;step++)
{
if(Thread.currentThread().getName().equals("兔子")&&step%10==0)
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"-->"+step);
boolean flag=gameOver(step);
if(flag)
{
break;
}
}
}
private boolean gameOver(int step)
{
if(winner!=null)
{
return true;
}else
{
if(step==100)
{
winner=Thread.currentThread().getName();
System.out.println("winner=="+winner);
return true;
}
}
return false;
}
public static void main(String[]args)
{ //一份資源
ThreadDownload td=new ThreadDownload();
new Thread(td,"烏龜").start();
new Thread(td,"兔子").start();
}
}
本文標(biāo)題:java多線程-資源共享
文章地址:http://aaarwkj.com/article22/goojjc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供軟件開發(fā)、做網(wǎng)站、移動網(wǎng)站建設(shè)、電子商務(wù)、網(wǎng)站排名、標(biāo)簽優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)