Java 作業 1202/1203


多線程
一、判斷題(T爲正確,F爲錯誤),每題11.如果線程死亡,它便不能運行。(T)
2.在Java中,高優先級的可運行線程會搶佔低優先級線程。(T)
3.線程可以用yield方法使低優先級的線程運行。(F)
4...程序開發者必須創建一個線程去管理內存的分配。(F)
5.一個線程在調用它的start方法,之前,該線程將一直處於出生期。(T)
6.當調用一個正在進行線程的stop( )方法時,該線程便會進入休眠狀態。(F)
7.一個線程可以調用yield方法使其他線程有機會運行。(T)
8.多線程沒有安全問題(F)
9.多線程安全問題的解決方案可以使用Lock提供的具體的鎖對象操作(T)
10.Stop()方法是終止當前線程的一種狀態(T)

二、選擇題(不定項選擇題),每題21.Java語言中提供了一個▁D線程,自動回收動態分配的內存。
A.異步
B.消費者
C.守護
D.垃圾收集
2.Java語言避免了大多數的▁C錯誤。
A.數組下標越界
B.算術溢出
C.內存泄露 
D.非法的方法參數
3.有三種原因可以導致線程不能運行,它們是▁ACD。
A.等待
B.阻塞
C.休眠
D.掛起及由於I/O操作而阻塞
4.當▁A方法終止時,能使線程進入死亡狀態。
A.run
B.setPrority//更改線程優先級
C.yield//暫停當前線程的執行  執行其他線程
D.sleep//線程休眠
5.用▁B方法可以改變線程的優先級。
A.run
B.setPrority
C.yield
D.sleep
6.線程通過▁C▁方法可以使具有相同優先級線程獲得處理器。
A.run
B.setPrority
C.yield
D.sleep
7.線程通過▁D▁方法可以休眠一段時間,然後恢復運行。
A.run
B.setPrority
C.yield
D.sleep
8.方法resume( )負責重新開始▁▁D線程的執行。
A.被stop( )方法停止
B.被sleep( )方法停止
C.被wait( )方法停止
D.被suspend( )方法停止
9.▁B C D▁方法可以用來暫時停止當前線程的運行。
A.stop( )
B.sleep( )
C.wait( )
D.suspend( )
10.請問下列哪些類是定義在java.io包中的抽象類(A B D )
A.InputStream
B.OutputStream
C.PrintStream
D.Reader
E.FileInputStream
F.FileWriter

三、簡述題,每題51.簡述程序、進程和線程之間的關係?什麼是多線程程序?
一個程序可以有多個進程 一個進程可以有多個線程
多線程:
一個進程裏開啓了多個線程,每個線程都在搶佔CPU的執行權
3.什麼是線程調度?Java的線程調度採用什麼策略?
按照一定的策略將CPU的執行權分配給線程
時間片輪轉加優先級
4.如何在Java程序中實現多線程?

        多線程的實現方式1:
            1) 創建一個自定義類,繼承Thread2) 重寫自定義類中的run()方法
            3) 在主程序中,創建自定義的類的對象,通過star()方法啓動它

        多線程的實現方式2:
            1) 自定義類,該類實現Runnable接口
            2) 實現接口中的run()方法
            3  在主程序中,創建該類對象的實例
            4) 再創建Thread類的對象,將步驟3中創建的對象當做參數傳遞進去
            5) 通過star()方法啓動它
多線程實現的方式3:
            1)自定義類中實現Callable接口,實現call()方法
            2)創建線程池對象public static ExecutorService newFixedThreadPool(int nThreads)
                參數是直接指定在當前線程池中有多少個線程
            3)<T> Future<T> submit(Callable<T> task)
                該返回值表示:異步計算的結果!
                Threadpool.submit(new MyCallable()) 
            4)Threadpool.shutdown() 
                結束線程池
5.試簡述Thread類的子類或實現Runnable接口兩種方法的異同?    
相同: 都重寫了run方法 都可以實現多線程
不同; Thread類子類實現多線程是通過創建子類對象然後調用star方法
實現Runnable接口是創建子接口對象,然後將對象當做參數傳入到Thread對象的構造方法中,再調用star方法
6.說明緩衝流的優點和原理
優點: 節省內存 速度快
原理; 創建一個緩衝區 將數據放到緩衝區裏 
8:在Java中wait()和sleep()方法的不同?
Wait是讓當前線程等待   sleep是過...秒之後執行
9:Java中Runnable和Callable有什麼不同?
.   Runnable接口不用寫泛型,Callable要寫泛型
Runnable實現run方法  Callable實現call方法

四、程序設計題
1.編寫一個應用程序,在線程同步的情況下來實現“生產者―消費者”問題。

2.修改上題,由於各個線程是異步運行的,因此無法預計其相對速度,爲了使生產者能夠不斷地生產,可以使用循環緩衝區,保證有足夠多的內存區保存更多的產品。(生產者——倉庫——消費者) 


3 :
1)將若干個Student對象;若干個Teacher對象,寫出到d:/0404/a.txt中,
  2)將該文件中所有的Student對象反序列化回來,裝入List,所有的Teacher對象反序列化回來裝入另一個List

4:實現字符串和字節數組之間的相互轉換,比如:將字符串”西部開源技術中心xbkyjszx”轉換爲字節數組,並將字節數組再轉換回字符串!
5:用Java編程一個會導致死鎖的程序,你將怎麼解決?請你設計

6:遞歸實現輸入任意目錄,列出文件以及文件夾

編程題:

package org.westos.Homework;

public class Homework01 {
    public static void main(String[] args) {
        Student s = new Student();

        GetThread gt = new GetThread(s);
        SetThread st = new SetThread(s);
        Thread t1 = new Thread(gt);
        Thread t2 = new Thread(st);
        t1.start();
        t2.start();
    }
}
package org.westos.Homework;

public class GetThread implements Runnable{
    private Student s;
    public GetThread (Student s) {
        this.s = s;
    }
    @Override
    public void run() {
        while(true) {
            synchronized (s) {
            if(!s.flag) {
                try {
                    s.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

                System.out.println(s.name+"----"+s.age);
                s.flag = false;
                s.notify();
            }

        }
    }
}

package org.westos.Homework;

public class SetThread implements Runnable{
    private Student s;
    public SetThread (Student s) {
        this.s = s;
    }
    private int x = 0;
    @Override
    public void run() {
        while(true) {
            synchronized (s) {
                if(s.flag) {
                    try {
                        s.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                if(x%2==0) {
                    s.name = "流通";
                    s.age = 18;
                }else {
                    s.name = "趙歡";
                    s.age = 20;
                }
                x++;
                s.flag = true;
                s.notify();
            }

        }

    }

}

package org.westos.Homework;

public class Student {
    String name;
    int age;
    boolean flag;
}

這裏寫圖片描述

package org.westos.Homework02;


public class Homework01 {
    public static void main(String[] args) {
        Student s = new Student("流通",18,100);
        GetThread gt = new GetThread(s);
        SetThread st = new SetThread(s);
        Thread t1 = new Thread(gt);
        Thread t2 = new Thread(st);
        t1.start();
        t2.start();

    }
}
package org.westos.Homework02;

public class GetThread implements Runnable {
    private Student s;


    public GetThread(Student s) {
        this.s = s;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (s) {
                if (s.number <= 0) {
                    try {
                        s.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                s.number--;
                System.out.println("還剩" + s.number + "個");
                s.notify();

            }

        }

    }

}
package org.westos.Homework02;

public class SetThread implements Runnable {
    private Student s;

    public SetThread(Student s) {
        this.s = s;

    }

    @Override
    public void run() {
        while (true) {
            synchronized (s) {
                if (s.number >= 300) {
                    try {
                        s.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                s.number++;
                System.out.println("倉庫有" + s.number + "個");
                s.notify();
            }

        }

    }

}
package org.westos.Homework02;

public class Student {
    String name;
    int age;
    int number;
    public Student() {

    }

    public Student(String name, int age, int number) {
        super();
        this.name = name;
        this.age = age;
        this.number = number;
    }

    public String toString() {
        return name+"--"+age;

    }
}

這裏寫圖片描述

package org.westos.Homework03;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

/**
 * 3 : 1)將若干個Student對象;若干個Teacher對象,寫出到d:/0404/a.txt中,
 * 2)將該文件中所有的Student對象反序列化回來,裝入List,所有的Teacher對象反序列化回來裝入另一個List
 */
public class Homework01 {
    public static void main(String[] args) throws Exception {
        method1();
        method2();
    }

    private static void method2() throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\0404\\a.txt"));
        ArrayList al = new ArrayList();
        ArrayList<Student> al1 = new ArrayList<Student>();
        ArrayList<Teacher> al2 = new ArrayList<Teacher>();
        al = (ArrayList) ois.readObject();
        for (Object a : al) {
            if (a instanceof Student) {
                al1.add((Student) a);
            } else {
                al2.add((Teacher) a);
            }
        }
        System.out.println("Student:" + al1);
        System.out.println("Teacher:" + al2);
    }

    private static void method1() throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\0404\\a.txt"));
        ArrayList al = new ArrayList();
        al.add(new Student("流通", 18));
        al.add(new Student("趙歡", 20));
        al.add(new Teacher("瑤瑤", 19));
        al.add(new Teacher("老王", 10));
        oos.writeObject(al);
        oos.close();

    }
}

這裏寫圖片描述

package org.westos.Homework04;

/**
 * :實現字符串和字節數組之間的相互轉換,比如:將字符串”西部開源技術中心xbkyjszx”轉換爲字節數組, 並將字節數組再轉換回字符串!
 */
public class Homework04 {
    public static void main(String[] args) {
        String str = "西部開源技術中心xbkyjszx";
        // 字符串轉成字節數組
        System.out.println("字符串轉成字節數組:");
        byte[] bytes = str.getBytes();
        for (byte b : bytes) {
            System.out.print(b + " ");
        }
        System.out.println();
        // 字節數組轉換成字符串
        System.out.println("字節數組轉換成字符串:");
        String s = new String(bytes);
        System.out.println(s);

    }

}

這裏寫圖片描述

package org.westos.Homework05;
/**
 * :用Java編程一個會導致死鎖的程序,你將怎麼解決?請你設計
 *      解決辦法:
 *          不讓兩個線程請求同一個鎖對象
 *              鎖對象改爲this
 * */
class Demo1 implements Runnable {
    private int a;
    private int b;

    public Demo1() {
        super();
    }

    public Demo1(int a, int b) {
        super();
        this.a = a;
        this.b = b;
    }

    @Override
    public void run() {
        synchronized (Integer.valueOf(a)) {
            synchronized (Integer.valueOf(b)) {
                System.out.println(a + b);
            }
        }

    }

}

public class Homework05 {
    public static void main(String[] args) {

        for (int i = 0; i < 20; i++) {
            new Thread(new Demo1(1, 2)).start();
            new Thread(new Demo1(2, 1)).start();
        }
    }
}

這裏寫圖片描述

package org.westos.Homework06;

import java.io.File;

/**
 * 6:遞歸實現輸入任意目錄,列出文件以及文件夾
 */
public class Homework06 {
    public static void main(String[] args) {
        File file = new File("D://0404");
        show(file);
    }

    private static void show(File file) {
        File[] fl = file.listFiles();
        for (File f : fl) {
            if (f.isDirectory()) {
                show(f);
            } else if (f.isFile()) {
                System.out.println(f);
            }
        }
        System.out.println(file);
    }
}

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章