java线程示例

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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类的方法:这个类有一个大小的方法,和减数量的方法,用于线程来减,当减到时,减的方法不在运行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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()

 

posted @   稷下元歌  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2022-09-15 (广州南沙)vue知识点整理2021,主要是防止忘记防备快速翻看
点击右上角即可分享
微信分享提示