? ? ? ? 题目?设计一个名为EnergyManager的类,实现了Runnable接口,int 类型成员变量 energy,初始值为0,设计一个同步方法,action(String name),如果线程名为walk消耗5个能量值,并输出“energy -5”, 如果能量值为0时,需要等待能量值增加到5个以上再消耗,并输出"no energy",如果线程名为eat,增加5个能量值,并输出“energy +5", 如果能量值为10,需要等待其小于10再增加,并输出"overload"。在run方法中调用action方法。
测试 | Result |
---|---|
EnergyManager em=new EnergyManager(); Thread t1=new Thread(em); t1.setName("walk"); t1.start(); Thread.sleep(10); Thread t2=new Thread(em); t2.setName("eat"); t2.start(); | no energy energy +5 energ |
?
import java.io.*;
public class Main {
public static void main(String[] args) throws InterruptedException {
EnergyManager em=new EnergyManager();
Thread t1=new Thread(em);
t1.setName("walk");
t1.start();
Thread.sleep(10);
Thread t2=new Thread(em);
t2.setName("eat");
t2.start();
}
}
class EnergyManager implements Runnable
{
int energy = 0;
synchronized void action(String name) throws Exception
{
if(name.equals("walk"))
{
while(energy<5)
{
System.out.println("no energy");
wait();
}
energy =energy-5;
System.out.println("energy-5");
} else if (name.equals("eat"))
{
while(energy>=10)
{
System.out.println("overload");
wait();
}
energy =energy+5;
System.out.println("energy+5");
}
notifyAll();
}
@Override
public void run()
{
try
{
action(Thread.currentThread().getName());
}catch (Exception e)
{
e.printStackTrace();
}
}
}
? ? ? ? 题目?创建一个名为MyFileReader的类,设计一个方法 char read(String fileName, int n),该读取名为fileName的文件,返回文件中第n个字符(n从1开始计数)
测试 | Result |
---|---|
MyFileReader mfr=new MyFileReader(); System.out.println(mfr.read("/home/java/2018test.txt",2)); | a |
import java.io.*;
public class Main {
public static void main(String[] args) throws InterruptedException {
MyFileReader mfr=new MyFileReader();
System.out.println(mfr.read("D:\\test1\\a.txt",2));
}
}
class MyFileReader
{
BufferedReader re = null;
char read(String fileName, int n)
{
try
{
re =new BufferedReader(new FileReader(fileName));
re.skip(n-1);
return (char)re.read();
}catch (Exception e)
{
e.printStackTrace();
}finally {
try {
if (re != null) {
re.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return '\0'; // 返回空字符,表示读取失败
}
}
?
? ? ? ? 题目?某科学生成绩在数据库提取出成字符串如下格式:“Tom:85,Jack:70,Black:95”
设计一个方法int getMax(String s),返回字符串s中的最高分。例如:
测试 | Result |
---|---|
MyUtil mu=new MyUtil(); String s="Tom:85,Jack:70,Black:95"; System.out.println(mu.getMax(s)); | 95 |
? ? ? ? 代码如下 :
import java.io.*;
public class Main {
public static void main(String[] args){
MyUtil mu=new MyUtil();
String s="Tom:85,Jack:70,Black:95";
System.out.println(mu.getMax(s));
}
}
class MyUtil {
int getMax(String s) {
String a[] = s.split(",");
int total = 0;
for (int i = 0; i < a.length; i++) {
String b[] = a[i].split(":");
int score = Integer.parseInt(b[1]);
if (score >= total) {
total = score;
}
}
return total;
}
}
?
?