将小段java代码转换为Delphi

xuchaobj 2005-04-20 07:19:16
小弟刚学delphi不久,想请大虾帮忙小弟起个头,将java代码转换为console application 中的代码,或者给个意思也成!

import java.math.*;
public class dinner {
boolean ch[]=new boolean[6];
/** Creates a new instance of dinner */
public dinner() {
for(int i=0;i<6;i++)
ch=true;
//philosopher ph=new philosopher(2,1,3);
philosopher1 ph1=new philosopher1();
philosopher2 ph2=new philosopher2();
philosopher3 ph3=new philosopher3();
philosopher4 ph4=new philosopher4();
philosopher5 ph5=new philosopher5();
System.out.println("问题描述:");
System.out.println("五个哲学家在一个桌子上进餐,他们每两个之间只有一根筷子,只有拿到两根筷子才能进餐。看他们是怎么协调的:");
ph1.setPriority((int)(Math.random()*10));//随机设置优先级 可选的
ph2.setPriority((int)(Math.random()*10));//随机设置优先级
ph3.setPriority((int)(Math.random()*10));//随机设置优先级
ph4.setPriority((int)(Math.random()*10));//随机设置优先级
ph5.setPriority((int)(Math.random()*10));//随机设置优先级
ph2.start();
ph1.start();
ph3.start();
ph4.start();
ph5.start();
while(!ph1.haveEaren()||!ph2.haveEaren()||!ph3.haveEaren()||!ph4.haveEaren()||!ph5.haveEaren());//等待所有线程结束,这个循环耗费cpu资源非同小可
System.out.println("全部哲学家用餐完毕!");


}

/************哲学家1********/
class philosopher1 extends Thread
{
boolean haveEaten=false,get1=false,get5=false;

philosopher1()//构造方法
{
haveEaten=false;
get1=false;
get5=false;
}
boolean haveEaren()//判断是否吃过了
{
if(haveEaten) return true;
else return false;
}
int whichIsWanted()
{
if(get1==true) return 5;
if(get5==true) return 1;
else
return 0;
}

int whichHaveGot()
{
if(get1==true)
return 1;
if(get5==true)
return 5;
else return 0;
}

public void run()
{
try{
while(!haveEaten)//如果还没吃饭
{
while(ch[1]||ch[5])
{
if(ch[1])
{ch[1]=false;get1=true;System.out.println("哲学家1拿起右边的筷子");}
if(ch[5])
{ch[5]=false;get5=true;System.out.println("哲学家1拿起左边的的筷子");}
if(!get1||!get5) //如果两根筷子没有全拿
{
int want=whichIsWanted();
int got=whichHaveGot();
int i;
for( i=0;i<5&&!ch[want];i++)//试图拿起另一根筷子,只有5秒的机会否则全部放弃
{
if(ch[want]==true)//如果可用
{
System.out.println("哲学家1拿起另一根的筷子");
ch[want]=false;
break;
}
sleep(1000);//等待一秒再试
}
if(i>=5)//如果拿了几次都没有拿起
{ ch[got]=true;//放弃机会
get1=false;
get5=false;
System.out.println("哲学家1试了五次最终没能拿起另一根筷子,现在只好把已拿到的一根筷子放下让别人使用,自己等会儿再吃。");
sleep(2500);
}
}
if(get1&&get5)//如果全拿起了
{
System.out.println("哲学家1正在用餐....");
sleep(10000);//吃饭时间10秒
ch[1]=true;
ch[5]=true;
haveEaten=true;
System.out.println("哲学家1用餐完毕,放下了筷子开始思考。");
stop();//终止线程
}

}
}

}//try end

catch (Exception e)
{e.printStackTrace();}
}
}
...全文
77 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xuchaobj 2005-04-21
  • 打赏
  • 举报
回复
不是正在学delphi 吗,希望大虾帮帮忙了
beyondtkl 2005-04-21
  • 打赏
  • 举报
回复
你算法都弄清楚了 重新寫一個就是呀

干嗎還要轉換。。
masterjames 2005-04-21
  • 打赏
  • 举报
回复
应该不难转
redlegend_126_com 2005-04-21
  • 打赏
  • 举报
回复
关于转换,希望你把java和Delphi都学精了,那就没有问题了!!哈哈

16,748

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 语言基础/算法/系统设计
社区管理员
  • 语言基础/算法/系统设计社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧