java菜鸟学习实例(四)

java实例


java菜鸟学习实例(一)
java菜鸟学习实例(二)
java菜鸟学习实例(三)
java菜鸟学习实例(四)
java菜鸟学习实例(完整版)

十.Java 集合

1.Java 实例 – 数组转集合

import java.util.*;
import java.io.*;
 
public class ArrayToCollection{
    
    
   public static void main(String args[]) 
   throws IOException{
    
    
      int n = 5;         // 5 个元素
      String[] name = new String[n];
      for(int i = 0; i < n; i++){
    
    
         name[i] = String.valueOf(i);
      }
      List<String> list = Arrays.asList(name); 
      System.out.println();
      for(String li: list){
    
    
         String str = li;
         System.out.print(str + " ");
      }
   }
}

2.Java 实例 – 集合比较

import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
 
class Main {
    
    
    public static void main(String[] args) {
    
    
        String[] coins = {
    
     "Penny", "nickel", "dime", "Quarter", "dollar" };
        Set<String> set = new TreeSet<String>();
        for (int i = 0; i < coins.length; i++) {
    
    
            set.add(coins[i]);
        }
        System.out.println(Collections.min(set));
        System.out.println(Collections.min(set, String.CASE_INSENSITIVE_ORDER));
        for (int i = 0; i <= 10; i++) {
    
    
            System.out.print("-");
        }
        System.out.println("");
        System.out.println(Collections.max(set));
        System.out.println(Collections.max(set, String.CASE_INSENSITIVE_ORDER));
    }
}

3.Java 实例 – HashMap遍历

import java.util.*;
 
public class Main {
    
    
   public static void main(String[] args) {
    
    
      HashMap< String, String> hMap = 
      new HashMap< String, String>();
      hMap.put("1", "1st");
      hMap.put("2", "2nd");
      hMap.put("3", "3rd");
      Collection cl = hMap.values();
      Iterator itr = cl.iterator();
      while (itr.hasNext()) {
    
    
         System.out.println(itr.next());
     }
   }
}

4.Java 实例 – 集合长度

import java.util.*;
 
public class Main {
    
    
   public static void main(String [] args) {
    
       
      System.out.println( "集合实例!\n" ); 
      int size;
      HashSet collection = new HashSet ();
      String str1 = "Yellow", str2 = "White", str3 = 
      "Green", str4 = "Blue";  
      Iterator iterator;
      collection.add(str1);    
      collection.add(str2);   
      collection.add(str3);   
      collection.add(str4);
      System.out.print("集合数据: ");  
      iterator = collection.iterator();     
      while (iterator.hasNext()){
    
    
         System.out.print(iterator.next() + " ");  
      }
      System.out.println();
      size = collection.size();
      if (collection.isEmpty()){
    
    
         System.out.println("集合是空的");
      }
      else{
    
    
         System.out.println( "集合长度: " + size);
      }
      System.out.println();
   }
}

5.Java 实例 – 集合打乱顺序

import java.util.*;
 
public class Main {
    
    
    public static void main(String[] args) {
    
    
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 10; i++)
            list.add(new Integer(i));
        System.out.println("打乱前:");
        System.out.println(list);
 
        for (int i = 1; i < 6; i++) {
    
    
            System.out.println("第" + i + "次打乱:");
            Collections.shuffle(list);
            System.out.println(list);
        }
    }
}

6.Java 实例 – 集合遍历

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
 
public class Main {
    
    
 
   public static void main(String[] args) {
    
    
      // List集合的遍历
      listTest();
      // Set集合的遍历
      setTest();
   }
 
   private static void setTest() {
    
    
      Set<String> set = new HashSet<String>();
      set.add("JAVA");
      set.add("C");
      set.add("C++");
      // 重复数据添加失败
      set.add("JAVA");
      set.add("JAVASCRIPT");
 
      // 使用iterator遍历set集合
      Iterator<String> it = set.iterator();
      while (it.hasNext()) {
    
    
         String value = it.next();
         System.out.println(value);
      }
      
      // 使用增强for循环遍历set集合
      for(String s: set){
    
    
         System.out.println(s);
      }
   }
 
   // 遍历list集合
   private static void listTest() {
    
    
      List<String> list = new ArrayList<String>();
      list.add("菜");
      list.add("鸟");
      list.add("教");
      list.add("程");
      list.add("www.runoob.com");
 
      // 使用iterator遍历
      Iterator<String> it = list.iterator();
      while (it.hasNext()) {
    
    
         String value = it.next();
         System.out.println(value);
      }
 
      // 使用传统for循环进行遍历
      for (int i = 0, size = list.size(); i < size; i++) {
    
    
         String value = list.get(i);
         System.out.println(value);
      }
 
      // 使用增强for循环进行遍历
      for (String value : list) {
    
    
         System.out.println(value);
      }
   }
}

7.Java 实例 – 集合反转

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
 
class Main {
    
    
   public static void main(String[] args) {
    
    
      String[] coins = {
    
     "A", "B", "C", "D", "E" };
      List l = new ArrayList();
      for (int i = 0; i < coins.length; i++)
         l.add(coins[i]);
      ListIterator liter = l.listIterator();
      System.out.println("反转前");
      while (liter.hasNext())
         System.out.println(liter.next());
      Collections.reverse(l);
      liter = l.listIterator();
      System.out.println("反转后");
      while (liter.hasNext())
         System.out.println(liter.next());
   }
}

8.Java 实例 – 删除集合中指定元素

import java.util.*;
 
public class Main {
    
    
   public static void main(String [] args) {
    
       
      System.out.println( "集合实例!\n" ); 
      int size;
      HashSet collection = new HashSet ();
      String str1 = "Yellow", str2 = "White", str3 = 
      "Green", str4 = "Blue";  
      Iterator iterator;
      collection.add(str1);    
      collection.add(str2);   
      collection.add(str3);   
      collection.add(str4);
      System.out.print("集合数据: ");  
      iterator = collection.iterator();     
      while (iterator.hasNext()){
    
    
         System.out.print(iterator.next() + " ");  
      }
      System.out.println();
      collection.remove(str2);
      System.out.println("删除之后 [" + str2 + "]\n");
      System.out.print("现在集合的数据是: ");
      iterator = collection.iterator();     
      while (iterator.hasNext()){
    
    
         System.out.print(iterator.next() + " ");  
      }
      System.out.println();
      size = collection.size();
      System.out.println("集合大小: " + size + "\n");
   }
}

9.Java 实例 – 只读集合

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
public class Main {
    
    
   public static void main(String[] argv) 
   throws Exception {
    
    
      List stuff = Arrays.asList(new String[] {
    
     "a", "b" });
      List list = new ArrayList(stuff);
      list = Collections.unmodifiableList(list);
      try {
    
    
         list.set(0, "new value");
      } 
        catch (UnsupportedOperationException e) {
    
    
      }
      Set set = new HashSet(stuff);
      set = Collections.unmodifiableSet(set);
      Map map = new HashMap();
      map = Collections.unmodifiableMap(map);
      System.out.println("集合现在是只读");
   }
}

10.Java 实例 – 集合输出

import java.util.*;
 
public class Main{
    
    
   public static void main(String[] args) {
    
    
      System.out.println("TreeMap 实例!\n");
      TreeMap tMap = new TreeMap();
      tMap.put(1, "Sunday");
      tMap.put(2, "Monday");
      tMap.put(3, "Tuesday");
      tMap.put(4, "Wednesday");
      tMap.put(5, "Thursday");
      tMap.put(6, "Friday");
      tMap.put(7, "Saturday");
      System.out.println("TreeMap 键:" 
      + tMap.keySet());
      System.out.println("TreeMap 值:" 
      + tMap.values());
      System.out.println("键为 5 的值为: " + tMap.get(5)+ "\n");
      System.out.println("第一个键: " + tMap.firstKey() 
      + " Value: " 
      + tMap.get(tMap.firstKey()) + "\n");
      System.out.println("最后一个键: " + tMap.lastKey() 
      + " Value: "+ tMap.get(tMap.lastKey()) + "\n");
      System.out.println("移除第一个数据: " 
      + tMap.remove(tMap.firstKey()));
      System.out.println("现在 TreeMap 键为: " 
      + tMap.keySet());
      System.out.println("现在 TreeMap 包含: " 
      + tMap.values() + "\n");
      System.out.println("移除最后一个数据: " 
      + tMap.remove(tMap.lastKey()));
      System.out.println("现在 TreeMap 键为: " 
      + tMap.keySet());
      System.out.println("现在 TreeMap 包含: " 
      + tMap.values());
   }
}

11.Java 实例 – 集合转数组

import java.util.*;
 
public class Main{
    
    
   public static void main(String[] args){
    
    
      List<String> list = new ArrayList<String>();
      list.add("菜"); 
      list.add("鸟"); 
      list.add("教");
      list.add("程");
      list.add("www.runoob.com");
      String[] s1 = list.toArray(new String[0]); 
      for(int i = 0; i < s1.length; ++i){
    
    
         String contents = s1[i];
         System.out.print(contents);
     } 
   }
}

12.Java 实例 – List 循环移动元素

import java.util.*;
 
public class Main {
    
    
   public static void main(String[] args) {
    
    
      List list = Arrays.asList("one Two three Four five six".split(" "));
      System.out.println("List :"+list);
      Collections.rotate(list, 3);
      System.out.println("rotate: " + list);
   }
}

13.Java 实例 – 查找 List 中的最大最小值

import java.util.*;
 
public class Main {
    
    
   public static void main(String[] args) {
    
    
      List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
      System.out.println(list);
      System.out.println("最大值: " + Collections.max(list));
      System.out.println("最小值: " + Collections.min(list));
   }
}

14.Java 实例 – 遍历 HashTable 的键值

import java.util.Enumeration;
import java.util.Hashtable;
 
public class Main {
    
    
   public static void main(String[] args) {
    
    
      Hashtable ht = new Hashtable();
      ht.put("1", "One");
      ht.put("2", "Two");
      ht.put("3", "Three");
      Enumeration e = ht.keys();
      while (e.hasMoreElements()){
    
    
         System.out.println(e.nextElement());
      }
   }
}

15.Java 实例 – 使用 Enumeration 遍历 HashTable

import java.util.Enumeration;
import java.util.Hashtable;
 
public class Main {
    
    
   public static void main(String[] args) {
    
    
      Hashtable ht = new Hashtable();
      ht.put("1", "One");
      ht.put("2", "Two");
      ht.put("3", "Three");
      Enumeration e = ht.elements();
      while(e.hasMoreElements()){
    
    
         System.out.println(e.nextElement());
      }
   }
}

16.Java 实例 – 集合中添加不同类型元素

import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
 
 
public class Main {
    
    
   public static void main(String[] args) {
    
    
      List lnkLst = new LinkedList();
      lnkLst.add("element1");
      lnkLst.add("element2");
      lnkLst.add("element3");
      lnkLst.add("element4");
      displayAll(lnkLst);
      List aryLst = new ArrayList();
      aryLst.add("x");
      aryLst.add("y");
      aryLst.add("z");
      aryLst.add("w");
      displayAll(aryLst);
      Set hashSet = new HashSet();
      hashSet.add("set1");
      hashSet.add("set2");
      hashSet.add("set3");
      hashSet.add("set4");
      displayAll(hashSet);
      SortedSet treeSet = new TreeSet();
      treeSet.add("1");
      treeSet.add("2");
      treeSet.add("3");
      treeSet.add("4");
      displayAll(treeSet);
      LinkedHashSet lnkHashset = new LinkedHashSet();
      lnkHashset.add("one");
      lnkHashset.add("two");
      lnkHashset.add("three");
      lnkHashset.add("four");
      displayAll(lnkHashset);
      Map map1 = new HashMap();
      map1.put("key1", "J");
      map1.put("key2", "K");
      map1.put("key3", "L");
      map1.put("key4", "M");
      displayAll(map1.keySet());
      displayAll(map1.values());
      SortedMap map2 = new TreeMap();
      map2.put("key1", "JJ");
      map2.put("key2", "KK");
      map2.put("key3", "LL");
      map2.put("key4", "MM");
      displayAll(map2.keySet());
      displayAll(map2.values());
      LinkedHashMap map3 = new LinkedHashMap();
      map3.put("key1", "JJJ");
      map3.put("key2", "KKK");
      map3.put("key3", "LLL");
      map3.put("key4", "MMM");
      displayAll(map3.keySet());
      displayAll(map3.values());
   }
   static void displayAll(Collection col) {
    
    
      Iterator itr = col.iterator();
      while (itr.hasNext()) {
    
    
         String str = (String) itr.next();
         System.out.print(str + " ");
      }
      System.out.println();
   }
}

17.Java 实例 – List 元素替换

import java.util.*;
 
public class Main {
    
    
   public static void main(String[] args) {
    
    
      List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
      System.out.println("List :"+list);
      Collections.replaceAll(list, "one", "hundrea");
      System.out.println("replaceAll: " + list);
   }
}

18.Java 实例 – List 截取

import java.util.*;
 
public class Main {
    
    
   public static void main(String[] args) {
    
    
      List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
      System.out.println("List :"+list);
      List sublist = Arrays.asList("three Four".split(" "));
      System.out.println("子列表 :"+sublist);
      System.out.println("indexOfSubList: "
      + Collections.indexOfSubList(list, sublist));
      System.out.println("lastIndexOfSubList: "
      + Collections.lastIndexOfSubList(list, sublist));
   }
}

十一.Java 网络实例

1.Java 实例 – 获取指定主机的IP地址

import java.net.InetAddress;
import java.net.UnknownHostException;
 
public class GetIP {
    
    
    public static void main(String[] args) {
    
    
        InetAddress address = null;
        try {
    
    
            address = InetAddress.getByName("www.runoob.com");
        }
        catch (UnknownHostException e) {
    
    
            System.exit(2);
        }
        System.out.println(address.getHostName() + "=" + address.getHostAddress());
        System.exit(0);
    }
}

2.Java 实例 – 查看端口是否已使用

import java.net.*;
import java.io.*;
 
public class Main {
    
    
   public static void main(String[] args) {
    
    
      Socket Skt;
      String host = "localhost";
      if (args.length > 0) {
    
    
         host = args[0];
      }
      for (int i = 0; i < 1024; i++) {
    
    
         try {
    
    
            System.out.println("查看 "+ i);
            Skt = new Socket(host, i);
            System.out.println("端口 " + i + " 已被使用");
         }
         catch (UnknownHostException e) {
    
    
            System.out.println("Exception occured"+ e);
            break;
         }
         catch (IOException e) {
    
    
         }
      }
   }
}

3.Java 实例 – 获取本机ip地址及主机名

import java.net.InetAddress;
import java.net.UnknownHostException;
 
public class NetworkInfo {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            // 获取本地主机对象
            InetAddress localHost = InetAddress.getLocalHost();
            
            // 获取主机名
            String hostName = localHost.getHostName();
            System.out.println("主机名: " + hostName);
            
            // 获取IP地址
            String hostAddress = localHost.getHostAddress();
            System.out.println("IP地址: " + hostAddress);
        } catch (UnknownHostException e) {
    
    
            System.err.println("无法获取本机IP地址及主机名: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

4.Java 实例 – 获取远程文件大小

import java.net.URL;
import java.net.URLConnection;
 
public class Main {
    
    
   public static void main(String[] args) throws Exception {
    
    
      int size;
      URL url = new URL("http://www.runoob.com/wp-content/themes/runoob/assets/img/newlogo.png");
      URLConnection conn = url.openConnection();
      size = conn.getContentLength();
      if (size < 0)
          System.out.println("无法获取文件大小。");
      else
        System.out.println("文件大小为:" + size + " bytes");
      conn.getInputStream().close();
   }
}

5.Java 实例 – Socket 实现多线程服务器程序

import java.io.*;
import java.net.*;
 
public class MultiThreadedServer {
    
    
    public static void main(String[] args) {
    
    
        int port = 12345; // 定义服务器端口
        try (ServerSocket serverSocket = new ServerSocket(port)) {
    
    
            System.out.println("服务器已启动,等待客户端连接...");
 
            while (true) {
    
    
                Socket clientSocket = serverSocket.accept(); // 接受客户端连接
                System.out.println("客户端已连接: " + clientSocket.getInetAddress().getHostAddress());
 
                // 为每个客户端连接启动一个新的线程
                ClientHandler clientHandler = new ClientHandler(clientSocket);
                new Thread(clientHandler).start();
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}
 
class ClientHandler implements Runnable {
    
    
    private Socket clientSocket;
 
    public ClientHandler(Socket socket) {
    
    
        this.clientSocket = socket;
    }
 
    @Override
    public void run() {
    
    
        try (
            InputStream input = clientSocket.getInputStream();
            OutputStream output = clientSocket.getOutputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            PrintWriter writer = new PrintWriter(output, true)
        ) {
    
    
            String clientMessage;
            while ((clientMessage = reader.readLine()) != null) {
    
    
                System.out.println("收到客户端消息: " + clientMessage);
                writer.println("服务器回应: " + clientMessage); // 发送回应消息给客户端
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            try {
    
    
                clientSocket.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

6.Java 实例 – 查看主机指定文件的最后修改时间

import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.text.SimpleDateFormat;
 
public class Main {
    
    
    public static void main(String[] argv) throws Exception {
    
    
        URL u = new URL("http://127.0.0.1/test/test.html");
        URLConnection uc = u.openConnection();
        SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
        uc.setUseCaches(false);
        long timestamp = uc.getLastModified();
        System.out.println("test.html 文件最后修改时间 :" + ft.format(new Date(timestamp)));
    }
}

7.Java 实例 – 使用 Socket 连接到指定主机

import java.net.InetAddress;
import java.net.Socket;
 
public class WebPing {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            InetAddress addr;
            Socket sock = new Socket("www.runoob.com", 80);
            addr = sock.getInetAddress();
            System.out.println("连接到 " + addr);
            sock.close();
        } catch (java.io.IOException e) {
    
    
            System.out.println("无法连接 " + args[0]);
            System.out.println(e);
        }
    }
}

8.Java 实例 – 网页抓取

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;
 
public class Main {
    
    
   public static void main(String[] args) 
   throws Exception {
    
    
      URL url = new URL("http://www.runoob.com");
      BufferedReader reader = new BufferedReader
      (new InputStreamReader(url.openStream()));
      BufferedWriter writer = new BufferedWriter
      (new FileWriter("data.html"));
      String line;
      while ((line = reader.readLine()) != null) {
    
    
         System.out.println(line);
         writer.write(line);
         writer.newLine();
      }
      reader.close();
      writer.close();
   }
}

9.Java 实例 – 获取 URL响应头的日期信息

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
 
public class Main{
    
    
   public static void main(String args[]) 
   throws Exception {
    
    
      URL url = new URL("http://www.runoob.com");
      HttpURLConnection httpCon = 
      (HttpURLConnection) url.openConnection();
      long date = httpCon.getDate();
      if (date == 0)
      System.out.println("无法获取信息。");
      else
      System.out.println("Date: " + new Date(date));
   }
}

10.Java 实例 – 获取 URL 响应头信息

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Set;
 
public class Main {
    
    
    public static void main(String[] args) throws IOException{
    
    
        URL url = new URL("http://www.runoob.com");
        URLConnection conn = url.openConnection();
        
        Map headers = conn.getHeaderFields();
        Set<String> keys = headers.keySet();
        for( String key : keys ){
    
    
            String val = conn.getHeaderField(key);
            System.out.println(key+"    "+val);
        }
        System.out.println( conn.getLastModified() );
    }
}

11.Java 实例 – 解析 URL

import java.net.URL;
 
public class Main {
    
    
   public static void main(String[] args) 
   throws Exception {
    
    
      URL url = new URL("http://www.runoob.com/html/html-tutorial.html");
      System.out.println("URL 是 " + url.toString());
      System.out.println("协议是 " + url.getProtocol());
      System.out.println("文件名是 " + url.getFile());
      System.out.println("主机是 " + url.getHost());
      System.out.println("路径是 " + url.getPath());
      System.out.println("端口号是 " + url.getPort());
      System.out.println("默认端口号是 " 
      + url.getDefaultPort());
   }
}

12.Java 实例 – ServerSocket 和 Socket 通信实例

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
 
public class Server {
    
    
   public static void main(String[] args) {
    
    
      try {
    
    
         ServerSocket ss = new ServerSocket(8888);
         System.out.println("启动服务器....");
         Socket s = ss.accept();
         System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器");
         
         BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
         //读取客户端发送来的消息
         String mess = br.readLine();
         System.out.println("客户端:"+mess);
         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
         bw.write(mess+"\n");
         bw.flush();
      } catch (IOException e) {
    
    
         e.printStackTrace();
      }
   }
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
 
public class Client {
    
    
   public static void main(String[] args) {
    
    
      try {
    
    
         Socket s = new Socket("127.0.0.1",8888);
         
         //构建IO
         InputStream is = s.getInputStream();
         OutputStream os = s.getOutputStream();
         
         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
         //向服务器端发送一条消息
         bw.write("测试客户端和服务器通信,服务器接收到消息返回到客户端\n");
         bw.flush();
         
         //读取服务器返回的消息
         BufferedReader br = new BufferedReader(new InputStreamReader(is));
         String mess = br.readLine();
         System.out.println("服务器:"+mess);
      } catch (UnknownHostException e) {
    
    
         e.printStackTrace();
      } catch (IOException e) {
    
    
         e.printStackTrace();
      }
   }
}

十二.Java 线程

1.Java 实例 – 查看线程是否存活

public class TwoThreadAlive extends Thread {
    
    
   public void run() {
    
    
      for (int i = 0; i < 10; i++) {
    
    
         printMsg();
      }
   }
 
   public void printMsg() {
    
    
      Thread t = Thread.currentThread();
      String name = t.getName();
      System.out.println("name=" + name);
   }
 
   public static void main(String[] args) {
    
    
      TwoThreadAlive tt = new TwoThreadAlive();
      tt.setName("Thread");
      System.out.println("before start(), tt.isAlive()=" + tt.isAlive());
      tt.start();
      System.out.println("just after start(), tt.isAlive()=" + tt.isAlive());
      for (int i = 0; i < 10; i++) {
    
    
         tt.printMsg();
      }
      System.out.println("The end of main(), tt.isAlive()=" + tt.isAlive());
   }
}

2.Java 实例 – 获取当前线程名称

public class TwoThreadGetName extends Thread {
    
    
   public void run() {
    
    
      for (int i = 0; i < 10; i++) {
    
    
         printMsg();
      }
   }
   public void printMsg() {
    
    
      Thread t = Thread.currentThread();
      String name = t.getName();
      System.out.println("name=" + name);
   } 
   public static void main(String[] args) {
    
    
      TwoThreadGetName tt = new TwoThreadGetName();
      tt.start();
      for (int i = 0; i < 10; i++) {
    
    
         tt.printMsg();
      }
   }
}

3.Java 实例 – 状态监测

class MyThread extends Thread{
    
    
   boolean waiting= true;
   boolean ready= false;
   MyThread() {
    
    
   }
   public void run() {
    
    
      String thrdName = Thread.currentThread().getName();
      System.out.println(thrdName + " starting.");
      while(waiting) 
      System.out.println("waiting:"+waiting); 
      System.out.println("waiting...");
      startWait(); 
      try {
    
    
         Thread.sleep(1000);
      }
      catch(Exception exc) {
    
    
         System.out.println(thrdName + " interrupted.");
      }
      System.out.println(thrdName + " terminating.");
   }
   synchronized void startWait() {
    
    
      try {
    
    
         while(!ready) wait();
      }
      catch(InterruptedException exc) {
    
    
         System.out.println("wait() interrupted");
      }
   }
   synchronized void notice() {
    
    
      ready = true;
      notify();
   }
}
public class Main {
    
    
   public static void main(String args[]) 
   throws Exception{
    
    
      MyThread thrd = new MyThread();
      thrd.setName("MyThread #1");
      showThreadStatus(thrd);
      thrd.start();
      Thread.sleep(50);
      showThreadStatus(thrd);
      thrd.waiting = false;
      Thread.sleep(50); 
      showThreadStatus(thrd);
      thrd.notice();
      Thread.sleep(50);
      showThreadStatus(thrd);
      while(thrd.isAlive()) 
      System.out.println("alive");
      showThreadStatus(thrd);
   }
   static void showThreadStatus(Thread thrd) {
    
    
      System.out.println(thrd.getName() + "Alive:=" + thrd.isAlive() + " State:=" + thrd.getState());
   }
}

4.Java 实例 – 线程优先级设置

public class SimplePriorities extends Thread {
    
    
   private int countDown = 5;
   private volatile double d = 0; 
   public SimplePriorities(int priority) {
    
    
      setPriority(priority);
      start();
   }
   public String toString() {
    
    
      return super.toString() + ": " + countDown;
   }
   public void run() {
    
    
      while(true) {
    
    
         for(int i = 1; i < 100000; i++)
         d = d + (Math.PI + Math.E) / (double)i;
         System.out.println(this);
         if(--countDown == 0) return;
      }
   }
   public static void main(String[] args) {
    
    
      new SimplePriorities(Thread.MAX_PRIORITY);
      for(int i = 0; i < 5; i++)
      new SimplePriorities(Thread.MIN_PRIORITY);
   }
}

5.Java 实例 – 死锁及解决方法

import java.util.Date;
 
public class LockTest {
    
    
   public static String obj1 = "obj1";
   public static String obj2 = "obj2";
   public static void main(String[] args) {
    
    
      LockA la = new LockA();
      new Thread(la).start();
      LockB lb = new LockB();
      new Thread(lb).start();
   }
}
class LockA implements Runnable{
    
    
   public void run() {
    
    
      try {
    
    
         System.out.println(new Date().toString() + " LockA 开始执行");
         while(true){
    
    
            synchronized (LockTest.obj1) {
    
    
               System.out.println(new Date().toString() + " LockA 锁住 obj1");
               Thread.sleep(3000); // 此处等待是给B能锁住机会
               synchronized (LockTest.obj2) {
    
    
                  System.out.println(new Date().toString() + " LockA 锁住 obj2");
                  Thread.sleep(60 * 1000); // 为测试,占用了就不放
               }
            }
         }
      } catch (Exception e) {
    
    
         e.printStackTrace();
      }
   }
}
class LockB implements Runnable{
    
    
   public void run() {
    
    
      try {
    
    
         System.out.println(new Date().toString() + " LockB 开始执行");
         while(true){
    
    
            synchronized (LockTest.obj2) {
    
    
               System.out.println(new Date().toString() + " LockB 锁住 obj2");
               Thread.sleep(3000); // 此处等待是给A能锁住机会
               synchronized (LockTest.obj1) {
    
    
                  System.out.println(new Date().toString() + " LockB 锁住 obj1");
                  Thread.sleep(60 * 1000); // 为测试,占用了就不放
               }
            }
         }
      } catch (Exception e) {
    
    
         e.printStackTrace();
      }
   }
}

6.Java 实例 – 获取线程id

public class Main extends Object implements Runnable {
    
    
  private ThreadID var;
 
  public Main(ThreadID v) {
    
    
    this.var = v;
  }
 
  public void run() {
    
    
    try {
    
    
      print("var getThreadID =" + var.getThreadID());
      Thread.sleep(2000);
      print("var getThreadID =" + var.getThreadID());
    } catch (InterruptedException x) {
    
    
    }
  }
 
  private static void print(String msg) {
    
    
    String name = Thread.currentThread().getName();
    System.out.println(name + ": " + msg);
  }
 
  public static void main(String[] args) {
    
    
    ThreadID tid = new ThreadID();
    Main shared = new Main(tid);
 
    try {
    
    
      Thread threadA = new Thread(shared, "threadA");
      threadA.start();
 
      Thread.sleep(500);
 
      Thread threadB = new Thread(shared, "threadB");
      threadB.start();
 
      Thread.sleep(500);
 
      Thread threadC = new Thread(shared, "threadC");
      threadC.start();
    } catch (InterruptedException x) {
    
    
    }
  }
}
 
class ThreadID extends ThreadLocal {
    
    
  private int nextID;
 
  public ThreadID() {
    
    
    nextID = 10001;
  }
 
  private synchronized Integer getNewID() {
    
    
    Integer id = new Integer(nextID);
    nextID++;
    return id;
  }
 
 
  protected Object initialValue() {
    
    
    print("in initialValue()");
    return getNewID();
  }
 
  public int getThreadID() {
    
    
    Integer id = (Integer) get();
    return id.intValue();
  }
 
  private static void print(String msg) {
    
    
    String name = Thread.currentThread().getName();
    System.out.println(name + ": " + msg);
  }
}

7.Java 实例 – 线程挂起

public class SleepingThread extends Thread {
    
    
   private int countDown = 5;
   private static int threadCount = 0;
   public SleepingThread() {
    
    
      super("" + ++threadCount);
      start();
   }
   public String toString() {
    
     
      return "#" + getName() + ": " + countDown;
   }
   public void run() {
    
    
      while (true) {
    
    
         System.out.println(this);
         if (--countDown == 0)
            return;
         try {
    
    
            sleep(100);
         }
         catch (InterruptedException e) {
    
    
            throw new RuntimeException(e);
         }
      }
   }
   public static void main(String[] args) 
   throws InterruptedException {
    
    
      for (int i = 0; i < 5; i++)
      new SleepingThread().join();
      System.out.println("线程已被挂起");
   }
}

8.Java 实例 – 终止线程

public class ThreadInterrupt extends Thread 
{
    
     
    public void run() 
    {
    
     
        try 
        {
    
     
            sleep(50000);  // 延迟50秒 
        } 
        catch (InterruptedException e) 
        {
    
     
            System.out.println(e.getMessage()); 
        } 
    } 
    public static void main(String[] args) throws Exception 
    {
    
     
        Thread thread = new ThreadInterrupt(); 
        thread.start(); 
        System.out.println("在50秒之内按任意键中断线程!"); 
        System.in.read(); 
        thread.interrupt(); 
        thread.join(); 
        System.out.println("线程已经退出!"); 
    } 
}

9.Java 实例 – 生产者/消费者问题

/*
 author by runoob.com
 ProducerConsumerTest.java
 */

public class ProducerConsumerTest {
    
    
   public static void main(String[] args) {
    
    
      CubbyHole c = new CubbyHole();
      Producer p1 = new Producer(c, 1);
      Consumer c1 = new Consumer(c, 1);
      p1.start(); 
      c1.start();
   }
}
class CubbyHole {
    
    
   private int contents;
   private boolean available = false;
   public synchronized int get() {
    
    
      while (available == false) {
    
    
         try {
    
    
            wait();
         }
         catch (InterruptedException e) {
    
    
         }
      }
      available = false;
      notifyAll();
      return contents;
   }
   public synchronized void put(int value) {
    
    
      while (available == true) {
    
    
         try {
    
    
            wait();
         }
         catch (InterruptedException e) {
    
     
         } 
      }
      contents = value;
      available = true;
      notifyAll();
   }
}

class Consumer extends Thread {
    
    
   private CubbyHole cubbyhole;
   private int number;
   public Consumer(CubbyHole c, int number) {
    
    
      cubbyhole = c;
      this.number = number;
   }
   public void run() {
    
    
      int value = 0;
         for (int i = 0; i < 10; i++) {
    
    
            value = cubbyhole.get();
            System.out.println("消费者 #" + this.number+ " got: " + value);
         }
    }
}

class Producer extends Thread {
    
    
   private CubbyHole cubbyhole;
   private int number;

   public Producer(CubbyHole c, int number) {
    
    
      cubbyhole = c;
      this.number = number;
   }

   public void run() {
    
    
      for (int i = 0; i < 10; i++) {
    
    
         cubbyhole.put(i);
         System.out.println("生产者 #" + this.number + " put: " + i);
         try {
    
    
            sleep((int)(Math.random() * 100));
         } catch (InterruptedException e) {
    
     }
      }
   }
}

10.Java 实例 – 获取线程状态

// Java 程序 - 演示线程状态
class thread implements Runnable 
{
    
     
    public void run() 
    {
    
     
        //  thread2  - 超时等待
        try
        {
    
     
            Thread.sleep(1500); 
        }  
        catch (InterruptedException e)  
        {
    
     
            e.printStackTrace(); 
        } 
          
        System.out.println("State of thread1 while it called join() method on thread2 -"+ 
            Test.thread1.getState()); 
        try
        {
    
     
            Thread.sleep(200); 
        }  
        catch (InterruptedException e)  
        {
    
     
            e.printStackTrace(); 
        }      
    } 
} 
  
public class Test implements Runnable 
{
    
     
    public static Thread thread1; 
    public static Test obj; 
      
    public static void main(String[] args) 
    {
    
     
        obj = new Test(); 
        thread1 = new Thread(obj); 
          
        // 创建 thread1,现在是初始状态
        System.out.println("State of thread1 after creating it - " + thread1.getState()); 
        thread1.start(); 
          
        // thread1 - 就绪状态
        System.out.println("State of thread1 after calling .start() method on it - " +  
            thread1.getState()); 
    } 
      
    public void run() 
    {
    
     
        thread myThread = new thread(); 
        Thread thread2 = new Thread(myThread); 
          
        // 创建 thread1,现在是初始状态
        System.out.println("State of thread2 after creating it - "+ thread2.getState()); 
        thread2.start(); 
          
        // thread2 - 就绪状态
        System.out.println("State of thread2 after calling .start() method on it - " +  
            thread2.getState()); 
          
        // moving thread1 to timed waiting state 
        try
        {
    
     
            //moving - 超时等待
            Thread.sleep(200); 
        }  
        catch (InterruptedException e)  
        {
    
     
            e.printStackTrace(); 
        } 
        System.out.println("State of thread2 after calling .sleep() method on it - "+  
            thread2.getState() ); 
          
          
        try 
        {
    
     
            // 等待 thread2 终止
            thread2.join(); 
        }  
        catch (InterruptedException e)  
        {
    
     
            e.printStackTrace(); 
        } 
        System.out.println("State of thread2 when it has finished it's execution - " +  
            thread2.getState()); 
    } 
      
}

11.Java 实例 – 获取所有线程

public class Main extends Thread {
    
    
   public static void main(String[] args) {
    
    
      Main t1 = new Main();
      t1.setName("thread1");
      t1.start();
      ThreadGroup currentGroup = 
      Thread.currentThread().getThreadGroup();
      int noThreads = currentGroup.activeCount();
      Thread[] lstThreads = new Thread[noThreads];
      currentGroup.enumerate(lstThreads);
      for (int i = 0; i < noThreads; i++)
      System.out.println("线程号:" + i + " = " + lstThreads[i].getName());
   }
}

12.Java 实例 – 查看线程优先级

public class Main extends Object {
    
    
   private static Runnable makeRunnable() {
    
    
      Runnable r = new Runnable() {
    
    
         public void run() {
    
    
            for (int i = 0; i < 5; i++) {
    
    
               Thread t = Thread.currentThread();
               System.out.println("in run() - priority="
               + t.getPriority()+ ", name=" + t.getName());
               try {
    
    
                  Thread.sleep(2000);
               }
               catch (InterruptedException x) {
    
    
               }
            }
         }
      };
      return r;
   }
   public static void main(String[] args) {
    
    
      System.out.println("in main() - Thread.currentThread().getPriority()=" + Thread.currentThread().getPriority());
      System.out.println("in main() - Thread.currentThread().getName()="+ Thread.currentThread().getName());
      Thread threadA = new Thread(makeRunnable(), "threadA");
      threadA.start();
      try {
    
    
         Thread.sleep(3000);
      }
      catch (InterruptedException x) {
    
    
      }
      System.out.println("in main() - threadA.getPriority()="+ threadA.getPriority());
   }
}

13.Java 实例 – 中断线程

public class Main extends Object 
implements Runnable {
    
    
   public void run() {
    
    
      try {
    
    
         System.out.println("in run() - 将运行 work2() 方法");
         work2();
         System.out.println("in run() - 从 work2() 方法回来");
      }
      catch (InterruptedException x) {
    
    
         System.out.println("in run() - 中断 work2() 方法");
         return;
      }
      System.out.println("in run() - 休眠后执行");
      System.out.println("in run() - 正常离开");
   }
   public void work2() throws InterruptedException {
    
    
      while (true) {
    
    
         if (Thread.currentThread().isInterrupted()) {
    
    
            System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted());
            Thread.sleep(2000);
            System.out.println("D isInterrupted()=" + Thread.currentThread().isInterrupted());
         }
      }
   }
   public void work() throws InterruptedException {
    
    
      while (true) {
    
    
         for (int i = 0; i < 100000; i++) {
    
    
            int j = i * 2;
         }
         System.out.println("A isInterrupted()=" + Thread.currentThread().isInterrupted());
         if (Thread.interrupted()) {
    
    
            System.out.println("B isInterrupted()=" + Thread.currentThread().isInterrupted());
            throw new InterruptedException();
         }
      }
   }
   public static void main(String[] args) {
    
    
      Main si = new Main();
      Thread t = new Thread(si);
      t.start();
      try {
    
    
         Thread.sleep(2000);
      }
      catch (InterruptedException x) {
    
    
      }
      System.out.println("in main() - 中断其他线程");
      t.interrupt();
      System.out.println("in main() - 离开");
   }
}

java菜鸟学习实例(一)
java菜鸟学习实例(二)
java菜鸟学习实例(三)
java菜鸟学习实例(四)
java菜鸟学习实例(完整版)

猜你喜欢

转载自blog.csdn.net/qq_54122113/article/details/142868446