You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
方法一:用迭代器来删除后面三只羊
public void iteratorForRemove() {
Iterator<Sheep> it = sheepList.iterator();
int a = sheepList.size() - 1;
int i = 0;
while (it.hasNext()) {
Sheep sheep = (Sheep) it.next();
if (i > a - 3) {
it.remove();
}
i++;
}
}
方法二:用普通for循环来删除后面三只羊
public void forForRemove() {
int a = sheepList.size() - 1;
for (int i = sheepList.size() - 1; i > a - 3; i--) {
sheepList.remove(i);
}
}
方法三:用foreach来删除后面三只羊
public void foreachForRemove() {
for (Sheep sh : sheepList) {
if (i > a - 3) {
sheepList.remove(sh.name);
} else {
System.out.print(sh.name+" ");
}
i++;
}
}
作业2:自动写文件
File fe = new File("D://testforio");
try{
if(!fe.exists()){
fe.mkdir();
}
FileOutputStream fos = null;
File file = null;
for(int i = 1;i <= 10;i++){
file = new File(fe,"HelloWorld"+i+".txt");
fos = new FileOutputStream(file);
if(!file.exists()){
file.createNewFile();
}
String str ="我真 "+i;
byte[] b = str.getBytes();
fos.write(b);
fos.flush();
fos.close();
}
}catch(IOException e){
e.printStackTrace();
}
作业3.用代码实现比较Runnable和Thread的区别
class ThreadExtend implements Runnable{
int i = 5;
public void run(){
while(i > 0){
System.out.println(Thread.currentThread().getName()+"得到"+i);
i--;
}
}
}
public class MyRunnable {
public static void main(String[] args) {
ThreadExtend te = new ThreadExtend();
Thread h1 = new Thread(te,"first");
Thread h2 = new Thread(te,"second");
Thread h3 = new Thread(te,"third");
Thread h4 = new Thread(te,"fourth");
h1.start();
h2.start();
h3.start();
h4.start();
}
}
class ThreadExtend extends Thread{
String name;
public ThreadExtend(String name){
this.name = name;
}
int i = 5;
public void run(){
while(i > 0){
System.out.println(name+"得到"+i);
i--;
}
}
}
public class MyThread {
public static void main(String[] args) {
ThreadExtend h1 = new ThreadExtend("first");
ThreadExtend h2 = new ThreadExtend("second");
ThreadExtend h3 = new ThreadExtend("third");
ThreadExtend h4 = new ThreadExtend("fourth");
h1.start();
h2.start();
h3.start();
h4.start();
}
}
作业1:删羊
作业2:自动写文件
作业3.用代码实现比较Runnable和Thread的区别
- 区别
- 由于Java单继承特性导致了每一个类只能继承一个类,若继承了Thread类则无法继承别的类,而Runnable是接口,所以Runnable方式可以避免Thread方式由于Java单继承特性带来的缺陷
- Runnable的代码可以被多个线程(Thread实例)共享,适合于多个线程处理同一个资源的情况。
The text was updated successfully, but these errors were encountered: