java线程示例

发布时间 2023-09-15 14:59:39作者: 法师-谢双元

需要开启线程 的方法继承线程类,并在run  中写逻辑

public class Ant extends Thread{
    Cake cake;
    public Ant(String name,Cake cake){
        this.cake = cake;
        setName(name);

    }
    @Override
    public void run(){
        while (true){
            int n = 2;
            System.out.println(getName()+"吃"+n+"个蛋");
            cake.lost(n);
            System.out.println(getName()+"发现还剩"+cake.getSize() + "克");

            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
import java.awt.*;

public class TestMain {
    public static void main(String[] args) {
        Cake cake = new Cake();
        int size = 12;
        cake.setSize(size);
        System.out.println("蛋糕大小" + size +"");
        Ant antRed = new Ant("红蚂蚁",cake);
        Ant antBlak = new Ant("默哥哥",cake);
        antRed.start();
        antBlak.start();
    }
}

 

            if(cake.getSize() <=0){
                System.out.println(getName()+"也经进入死忙状态了");
                return;
            }
        }

    }
}

  配置cake类的方法:这个类有一个大小的方法,和减数量的方法,用于线程来减,当减到时,减的方法不在运行

public class Cake {
    int size;
    public void setSize(int n){
        size =n;
    }
    public int getSize(){
        return size;
    };
    public void lost(int m){
        if((size - m) >= 0){
            size = size -m;
        }

    }

}

  主类编写运行代,注意主类开启是 用run  而是start()