자바 다 중 스 레 드 - 안전 하지 않 은 스 레 드 수정
                                            
 2827 단어  자바
                    
티켓 강탈:
public class n {
public static void main(String[]args) throws InterruptedException
{
web wb=new web();
new Thread(wb,"a").start();
new Thread(wb,"b").start();
new Thread(wb,"c").start();
}
}
class web implements Runnable{
int num=10;
private boolean flag=true;
public void run()
{
while(flag)
{
    test();
}
}
public synchronized void test()//        , this  ,             ,     cpu  ,   
                            //             
{   if(num<0)
        {
    flag=false;
    return;
}
try {
    Thread.sleep(200);
}catch(InterruptedException e)
{
    e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+num--);
//     ,         ,      
//  :   1   ,        ,    ,        
//   :         ,          ,    
}
}  인출:
public class el {
public static void main(String[]args)
{
    account a=new account(100,"me");
    get g=new get(a,80,"she");
    get g2=new get(a,90,"he");
    g.start();
    g2.start();
}
}
//  
class account {
int money;
String name;
public account(int money,String name)
{
    this.money=money;
    this.name=name;
}
}
//    
class get extends Thread
{
account a; //     
int getmoney; //       
int getall; //       
public get (account a,int getmoney,String name)
{
    super(name);//Thread    name
    this.a=a;
    this.getmoney=getmoney;
}
public void run()
{
    test();
}
public /*synchronized */void test()//    ,    this,    account
{//  a.money account  ,              ,       
//       
    if(a.money<=0)
    {
        return;
    }
synchronized(a){
    if(a.money-getmoney<0) //     
    {
        return;
    }
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    a.money-=getmoney;
    getall+=getmoney;
    System.out.println(this.getName()+"-->     :"+a.money);
    System.out.println(this.getName()+"-->     :"+getall);
}
}
}  용기:
public class h {
public static void main(String[]args)
{
    List list=new ArrayList();
    for(int i=0;i<10000;i++)
    {
        new Thread(()->
        {synchronized(list) {
            list.add(Thread.currentThread().getName());}}
                ).start();
    }
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(list.size());
}
}  
                이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.