保存5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件
public class Task1 {
public static void main(String[] args) throws Exception {
// 1、保存5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件
Student s1 = new Student("name1", 88, 89, 90);
Student s2 = new Student("name2", 60, 97, 98);
Student s3 = new Student("name3", 78, 99, 87);
Student s4 = new Student("name4", 69, 89, 98);
Student s5 = new Student("name5", 78, 83, 91);
List<Student> students = new ArrayList<>();
students.add(s1);
students.add(s2);
students.add(s3);
students.add(s4);
students.add(s5);
Collections.sort(students, (a, b) -> {
if (a.getSum() > b.getSum())
return -1;
else return 1;
});
FileOutputStream fos=new FileOutputStream("testIO\\students.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
for(int i=0;i<students.size();i++){
oos.writeObject(students.get(i));
}
oos.close();
fos.close();
}
}
2、打印数字,读取通知
(1)在main方法中启动两个线程;
(2)在1个线程循环打印100以内的整数;
(3)直到第2个线程从键盘读取了“Q”命令。
public class MyThread extends Thread{
public static boolean lock=true;
}
public class MyThread1 extends MyThread {
static int i = 1;
@Override
public void run() {
while (true) {
if (lock ) {
lock=false;
System.out.println((i++) % 100);
lock=true;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
else {
// Thread.yield();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
public class MyThread2 extends MyThread {
Scanner scan = new Scanner(System.in);
@Override
public void run() {
Scanner scan = new Scanner(System.in);
while (true) {
if (lock) {
lock = false;
try {
this.join(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("线程2:请输入");
String s = scan.next();
if (s.equals("Q")) return;
lock = true;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
public class Task2 {
public static void main(String[] args) {
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
t1.setDaemon(true);
t1.start();
t2.start();
}
}