需要开启线程 的方法继承线程类,并在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()
标签:java,示例,int,Ant,Cake,线程,cake,public,size From: https://www.cnblogs.com/fgxwan/p/17705024.html