模拟抢票:
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();
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。