java多线程-资源共享

  • 单继承具有局限性,推荐使用Runnable接口,启动线程必须借用Thread类对象
    • new Thread(Run,String s).start() ,new Thread()可以传字符串
    • Thread.currentThread().getName();当前线程的名字,即传入的字符串
    • 重写的run()方法没有返回值,且不能抛出异常
    • Thread.sleep(200);暂停该线程200毫秒延迟,1000毫秒约等于一秒

模拟抢票:

创新互联主营钦州网站建设的网络公司,主营网站建设方案,app软件开发公司,钦州h5小程序开发搭建,钦州网站营销推广欢迎钦州等地区企业咨询

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();
}
}

本文题目:java多线程-资源共享
文章URL:http://cdiso.cn/article/goojjc.html

其他资讯