20155327《Java程序設計》第八週學習總結
教材學習內容總結
第12章html
進程與線程
進程的完成過程:代碼加載、執行至執行完畢
線程:一個進程由多個線程組成。
線程的完成過程:自身的產生、存在和消亡
關係:沒有進程就不會有線程
線程是運行在進程中的小線程。
線程
多線程:幾個執行體共同執行程序的過程。
注意:計算機在任何給定的時刻只能執行那些線程中的一個。
創建多線程機制:Java虛擬機快速地把控制從一個線程切換到另外一個線程,這些線程被輪流執行,每一個線程都有機會使用CPU資源。
主線程:JVM加載代碼時,發現main方法以後啓動的線程
線程的狀態:
新建
運行:使用start()方法
中斷
死亡
線程的建立
兩種方式:
使用Thread類子類建立:須要重寫run()方法。
使用Thread類
構造方法:Thread(Runable target)
須要建立一個Runnable接口類的事例,並在該接口中重寫run方法。
目標對象與線程的關係:徹底解耦和目標對象組合線程
線程中的經常使用方法:
start():注意使用start()方法後沒必要再讓線程調用start()方法。
run():Thread子類中重寫run()或在Runnable接口中編寫run()
sleep(int millsecond):使進程休眠。
注意:參數millsecond是以毫秒爲單位的休眠時間
必須在try-catch語句塊中調用sleep方法
4.isAlive():線程沒有進入死亡狀態,調用isAlive()方法返回true
線程進入死亡狀態後,調用isAlive()方法返回false
5.currentThread():返回正在使用CPU線程的線程。
6.interrupt():解除線程的休眠狀態。
線程同步: 程序中的若干個線程都須要使用一個方法,而這個方法用synchronized給予了修飾。
線程同步機制:線程A使用synchronized方法時,其餘線程想使用這個synchronized方法必須等待,直到線程A使用完該synchronized方法。
協調同步的線程:
1.wait():在同步方法中使用,使本線程等待,暫時讓出CPU的使用權。
2.notifyAll():通知全部因爲使用這個同步方法而處於等待的線程結束等待,曾中斷的線程就會從剛纔的中斷處繼續執行這個同步方法。
3.notify():通知處於等待中的線程的某一個結束等待。
++必須在同步方法中使用這三種方法++java
線程聯合
join():其餘線程調用該方法,能夠和正在使用CPU資源的線程聯合。
問題解決:
報錯以下:
Port 443 in use by 「C:\Linux\vm\vmware-hostd.exe -u 「C:\ProgramData\VMware\hostd\config.xml」」 with PID 3696!
.將 vmware-hostd.exe 的自動啓動改成手動啓動並將其中止。在桌面的計算機圖標點擊鼠標右鍵,選擇 「管理→服務和應用程序→服務」,將顯示名稱爲「VMware Workstation Server」的服務的啓動類型改成手動,並中止該服務便可。mysql
GUI線程
計時器線程:使用Time類
守護線程:使用void setDaemon(boolean on)方法sql
代碼託管數據庫
上週考試錯題總結
Q1:接口RowSet繼承了接口__,能夠調用RowSet中的方法__來填充其數據區。
①Statement ②ResultSet ③update ④populate
A . ①③
B . ①④
C . ②③
D . ②④apache
A1:正解:C
解析:與ResultSet相比較,
(1)RowSet擴展了ResultSet接口,所以能夠像使用ResultSet同樣使用RowSet。數組
(2)RowSet擴展了ResultSet接口,所以功能比ResultSet更多、更豐富。多線程
(3)默認狀況下,全部 RowSet 對象都是可滾動的和可更新的。而ResultSet是隻能向前滾動和只讀的。dom
(4)RowSet能夠是非連接的,而ResultSet是鏈接的。所以利用CacheRowSet接口能夠離線操做數據。學習
(5)RowSet接口添加了對 JavaBeans 組件模型的 JDBC API 支持。rowset 可用做可視化Bean開發環境中的 JavaBeans 組件。
(6)RowSet採用了新的鏈接數據庫的方法。
update經常使用於更新數據。
教材p332 Example11_1
提交運行結果截圖
1.修改數據庫表
2.運行代碼:
運行xampp時報錯以下:
Port 443 in use by 「C:\Linux\vm\vmware-hostd.exe -u 「C:\ProgramData\VMware\hostd\config.xml」」 with PID 3696!
解決方法:
.將 vmware-hostd.exe 的自動啓動改成手動啓動並將其中止。在桌面的計算機圖標點擊鼠標右鍵,選擇 「管理→服務和應用程序→服務」,將顯示名稱爲「VMware Workstation Server」的服務的啓動類型改成手動,並中止該服務便可
開啓成功:
. 下載附件中的world.sql.zip, 參考http://www.cnblogs.com/rocedu/p/6371315.html#SECDB,導入world.sql,提交導入成功截圖
編寫程序,查詢世界上的平均壽命最長和最短的國家
1.導入world.sql
2.編寫代碼:
查詢世界上超過「你學號前邊七位並把最後一位家到最高位,最高位爲0時置1」(好比學號20165201,超過3016520;學號20165208,超過1016520)的全部城市列表
/** * Created by lz50 on 2018/6/14. */ import java.sql.*; public class test2_1 { public static void main(String args[]) { Connection con=null; Statement sql; ResultSet rs; try{ Class.forName("com.mysql.jdbc.Driver"); //加載JDBC_MySQL驅動 } catch(Exception e){} String uri = "jdbc:mysql://localhost:3306/world?useSSL=true"; String user ="root"; String password =""; try{ con = DriverManager.getConnection(uri,user,password); //鏈接代碼 } catch(SQLException e){ } try { sql=con.createStatement(); rs=sql.executeQuery("SELECT * FROM city"); //查詢mess表 while(rs.next()) { int id=rs.getInt(1); String name=rs.getString(2); String countrycode=rs.getString(3); String district=rs.getString(4); int population=rs.getInt(5); if(population>9015532){ //20155327 System.out.printf("%d\t",id); System.out.printf("%s\t",name); System.out.printf("%s\t",countrycode); System.out.printf("%s\t",district); System.out.printf("%d\n",population); } } con.close(); } catch(SQLException e) { System.out.println(e); } } }
查詢人口:
import java.sql.*; public class test2_2 { public static void main(String [] args) { Connection con=null; Statement sql; ResultSet rs; String sqlStr = "select * from country where Region = 'Middle East'"; try{ Class.forName("com.mysql.jdbc.Driver"); //加載JDBC_MySQL驅動 } catch(Exception e){} String uri = "jdbc:mysql://localhost:3306/world?useSSL=true"; String user ="root"; String password =""; try{ con = DriverManager.getConnection(uri,user,password); //鏈接代碼 } catch(SQLException e){ } try { sql=con.createStatement(); rs = sql.executeQuery(sqlStr); int sum=0; while(rs.next()) { int population=rs.getInt(7); sum =sum+population; } System.out.printf("中東國家的總人口爲:"+sum); con.close(); } catch(SQLException e) { System.out.println(e); } } }
查詢世界上的平均壽命最長和最短的國家
import java.sql.*; public class test2_3 { public static void main(String [] args) { Connection con=null; Statement sql; ResultSet rs; float smzd=1000.0f,smzc=0.0f; String c=new String(""); String d=new String(""); String sqlStr = "select * from country order by LifeExpectancy"; try{ Class.forName("com.mysql.jdbc.Driver"); //加載JDBC_MySQL驅動 } catch(Exception e){} String uri = "jdbc:mysql://localhost:3306/world?useSSL=true"; String user ="root"; String password =""; try{ con = DriverManager.getConnection(uri,user,password); //鏈接代碼 } catch(SQLException e){ } try { sql=con.createStatement(); rs = sql.executeQuery(sqlStr); while(rs.next()) { String Name=rs.getString(2); Float LifeExpectancy=rs.getFloat(8); if(LifeExpectancy>smzc) { smzc =LifeExpectancy; c =Name; } else if(LifeExpectancy<smzd){ { smzd = LifeExpectancy; d = Name; } } } con.close(); System.out.printf("世界上平均壽命最長的國家爲:"+c+",平均壽命爲:"+smzc+"\n"); System.out.printf("世界上平均壽命最短的國家爲:"+d+",平均壽命爲:"+smzd+"\n"); } catch(SQLException e) { System.out.println(e); } } }
Example11_1 import java.sql.*; public class Example11_1 { public static void main(String args[]) { Connection con=null; Statement sql; ResultSet rs; try{ Class.forName("com.mysql.jdbc.Driver"); //加載JDBC_MySQL驅動 } catch(Exception e){} String uri = "jdbc:mysql://localhost:3306/students?useSSL=true"; String user ="root"; String password =""; try{ con = DriverManager.getConnection(uri,user,password); //鏈接代碼 } catch(SQLException e){ } try { sql=con.createStatement(); rs=sql.executeQuery("SELECT * FROM mess"); //查詢mess表 while(rs.next()) {//當存在下一個數據是返回true String number=rs.getString(1);//將表第一列的數據傳給number String name=rs.getString(2); Date date=rs.getDate(3); float height=rs.getFloat(4); System.out.printf("%s\t",number); System.out.printf("%s\t",name); System.out.printf("%s\t",date); System.out.printf("%.2f\n",height); } con.close();//關閉鏈接 } catch(SQLException e) { System.out.println(e); } } }
這個代碼是用來查詢student數據庫中的mess表的所有記錄。
Example11_2
import java.sql.*; public class Example11_2 { public static void main(String args[]) { Connection con; Statement sql; ResultSet rs; con = GetDBConnection.connectDB("students","root",""); if(con == null ) return; try { sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = sql.executeQuery("SELECT * FROM mess "); rs.last(); int max = rs.getRow(); System.out.println("表共有"+max+"條記錄,隨機抽取2條記錄:"); int [] a =GetRandomNumber.getRandomNumber(max,2);//獲得1-max之間2個不一樣隨機數 for(int i:a){ rs.absolute(i);//油標移動到第i行 String number = rs.getString(1); String name = rs.getString(2); Date date = rs.getDate(3); float h = rs.getFloat(4); System.out.printf("%s\t",number); System.out.printf("%s\t",name); System.out.printf("%s\t",date); System.out.printf("%.2f\n",h); } con.close(); } catch(SQLException e) { System.out.println(e); } } }
import java.sql.*; public class GetDBConnection { public static Connection connectDB(String DBName,String id,String p) { Connection con = null; String uri = "jdbc:mysql://localhost:3306/"+DBName+"?useSSL=true&characterEncoding=utf-8"; try{ Class.forName("com.mysql.jdbc.Driver");//加載JDBC-MySQL驅動 } catch(Exception e){} try{ con = DriverManager.getConnection(uri,id,p); //鏈接代碼 } catch(SQLException e){} return con; } } import java.util.*; public class GetRandomNumber { public static int [] getRandomNumber(int max,int amount) { //1-max之間的amount個不一樣隨機整數 int [] randomNumber = new int[amount]; int index =0; randomNumber[0]= -1; Random random = new Random(); while(index<amount){ int number = random.nextInt(max)+1; boolean isInArrays=false; for(int m:randomNumber){//m依次取數組randomNumber元素的值(見3.7) if(m == number) isInArrays=true; //number在數組裏了 } if(isInArrays==false){ //若是number不在數組randomNumber中: randomNumber[index] = number; index++; } } return randomNumber; } }
將數據庫單獨分裝在一個GetDatabaseConnection類中。隨機查詢student數據庫中的mess表的兩條記錄。
Example11_3
import java.sql.*; public class Example11_3 { public static void main(String args[]) { Connection con; Statement sql; ResultSet rs; con = GetDBConnection.connectDB("students","root",""); if(con == null ) return; String c1=" year(birthday)<=2000 and month(birthday)>7";//條件1 String c2=" name Like '張_%'"; String c3=" height >1.65"; String sqlStr = "select * from mess where "+c1+" and "+c2+" and "+c3+"order by birthday"; try { sql=con.createStatement(); rs = sql.executeQuery(sqlStr); while(rs.next()) { String number=rs.getString(1); String name=rs.getString(2); Date date=rs.getDate(3); float height=rs.getFloat(4); System.out.printf("%s\t",number); System.out.printf("%s\t",name); System.out.printf("%s\t",date); System.out.printf("%.2f\n",height); } con.close(); } catch(SQLException e) { System.out.println(e); } } }
import java.sql.*; public class GetDBConnection { public static Connection connectDB(String DBName,String id,String p) { Connection con = null; String uri = "jdbc:mysql://localhost:3306/"+DBName+"?useSSL=true&characterEncoding=utf-8"; try{ Class.forName("com.mysql.jdbc.Driver");//加載JDBC-MySQL驅動 } catch(Exception e){} try{ con = DriverManager.getConnection(uri,id,p); //鏈接代碼 } catch(SQLException e){} return con; } }
這個代碼是查詢mess表中姓張,身高大於16.5,出生年份爲2000或2000年以前,月份在七月份以後的學生,並按出生日期排序。
Example11_4
import java.sql.*; public class Example11_4 { public static void main(String args[]) { Connection con; Statement sql; ResultSet rs; con = GetDBConnection.connectDB("students","root",""); if(con == null ) return; String jiLu="('R11q','王三','2000-10-23',1.66),"+ "('R10q','李武','1989-10-23',1.76)"; //2條記錄 String sqlStr ="insert into mess values"+jiLu; try { sql=con.createStatement(); int ok = sql.executeUpdate(sqlStr); rs = sql.executeQuery("select * from mess"); while(rs.next()) { String number=rs.getString(1); String name=rs.getString(2); Date date=rs.getDate(3); float height=rs.getFloat(4); System.out.printf("%s\t",number); System.out.printf("%s\t",name); System.out.printf("%s\t",date); System.out.printf("%.2f\n",height); } con.close(); } catch(SQLException e) { System.out.println("記錄中number值不能重複"+e); } } }
這個代碼是在mess表中插入兩條記錄。
Example11_5
import java.sql.*; public class Example11_5 { public static void main(String args[]) { Connection con; PreparedStatement preSql; //預處理語句對象preSql ResultSet rs; con = GetDBConnection.connectDB("students","root",""); if(con == null ) return; String sqlStr ="insert into mess values(?,?,?,?)"; try { preSql = con.prepareStatement(sqlStr);//獲得預處理語句對象preSql preSql.setString(1,"A001"); //設置第1個?表明的值 preSql.setString(2,"劉偉"); //設置第2個?表明的值 preSql.setString(3,"1999-9-10"); //設置第3個?表明的值 preSql.setFloat(4,1.77f); //設置第4個?表明的值 int ok = preSql.executeUpdate(); sqlStr="select * from mess where name like ? "; preSql = con.prepareStatement(sqlStr);//獲得預處理語句對象preSql preSql.setString(1,"張%"); //設置第1個?表明的值 rs = preSql.executeQuery(); while(rs.next()) { String number=rs.getString(1); String name=rs.getString(2); Date date=rs.getDate(3); float height=rs.getFloat(4); System.out.printf("%s\t",number); System.out.printf("%s\t",name); System.out.printf("%s\t",date); System.out.printf("%.2f\n",height); } con.close(); } catch(SQLException e) { System.out.println("記錄中number值不能重複"+e); } } }
import java.sql.*; public class GetDBConnection { public static Connection connectDB(String DBName,String id,String p) { Connection con = null; String uri = "jdbc:mysql://localhost:3306/"+DBName+"?useSSL=true&characterEncoding=utf-8"; try{ Class.forName("com.mysql.jdbc.Driver");//加載JDBC-MySQL驅動 } catch(Exception e){} try{ con = DriverManager.getConnection(uri,id,p); //鏈接代碼 } catch(SQLException e){} return con; } }
此代碼是使用預處理語句向mess表添加並查詢了姓張的記錄
Example11_6
import javax.swing.*; public class Example11_6 { public static void main(String args[]) { String [] tableHead; String [][] content; JTable table ; JFrame win= new JFrame(); Query findRecord = new Query(); findRecord.setDatabaseName("students"); findRecord.setSQL("select * from mess"); content = findRecord.getRecord(); tableHead=findRecord.getColumnName(); table = new JTable(content,tableHead); win.add(new JScrollPane(table)); win.setBounds(12,100,400,200); win.setVisible(true); win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } import java.sql.*; public class Query { String databaseName=""; //數據庫名 String SQL; //SQL語句 String [] columnName; //所有字段(列)名 String [][] record; //查詢到的記錄 public Query() { try{ Class.forName("com.mysql.jdbc.Driver");//加載JDBC-MySQL驅動 } catch(Exception e){} } public void setDatabaseName(String s) { databaseName=s.trim(); } public void setSQL(String SQL) { this.SQL=SQL.trim(); } public String[] getColumnName() { if(columnName ==null ){ System.out.println("先查詢記錄"); return null; } return columnName; } public String[][] getRecord() { startQuery(); return record; } private void startQuery() { Connection con; Statement sql; ResultSet rs; String uri = "jdbc:mysql://localhost:3306/"+ databaseName+"?useSSL=true&characterEncoding=utf-8"; try { con=DriverManager.getConnection(uri,"root",""); sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); rs=sql.executeQuery(SQL); ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount();//字段數目 columnName=new String[columnCount]; for(int i=1;i<=columnCount;i++){ columnName[i-1]=metaData.getColumnName(i); } rs.last(); int recordAmount =rs.getRow(); //結果集中的記錄數目 record = new String[recordAmount][columnCount]; int i=0; rs.beforeFirst(); while(rs.next()) { for(int j=1;j<=columnCount;j++){ record[i][j-1]=rs.getString(j); //第i條記錄,放入二維數組的第i行 } i++; } con.close(); } catch(SQLException e) { System.out.println("請輸入正確的表名"+e); } } }
這段代碼的功能是將數據庫名以及SQL語句傳遞給Query類的對象。
Example11_7
import java.sql.*; public class Example11_7{ public static void main(String args[]){ Connection con = null; Statement sql; ResultSet rs; String sqlStr; con = GetDBConnection.connectDB("students","root",""); if(con == null ) return; try{ float n = 0.02f; con.setAutoCommit(false); //關閉自動提交模式 sql = con.createStatement(); sqlStr = "select name,height from mess where number='R1001'"; rs = sql.executeQuery(sqlStr); rs.next(); float h1 = rs.getFloat(2); System.out.println("事務以前"+rs.getString(1)+"身高:"+h1); sqlStr = "select name,height from mess where number='R1002'"; rs = sql.executeQuery(sqlStr); rs.next(); float h2 = rs.getFloat(2); System.out.println("事務以前"+rs.getString(1)+"身高:"+h2); h1 = h1-n; h2 = h2+n; sqlStr = "update mess set height ="+h1+" where number='R1001'"; sql.executeUpdate(sqlStr); sqlStr = "update mess set height ="+h2+" where number='R1002'"; sql.executeUpdate(sqlStr); con.commit(); //開始事務處理,若是發生異常直接執行catch塊 con.setAutoCommit(true); //恢復自動提交模式 String s = "select name,height from mess"+ " where number='R1001'or number='R1002'"; rs = sql.executeQuery(s); while(rs.next()){ System.out.println("事務後"+rs.getString(1)+ "身高:"+rs.getFloat(2)); } con.close(); } catch(SQLException e){ try{ con.rollback(); //撤銷事務所作的操做 } catch(SQLException exp){} } } }
import java.sql.*; public class GetDBConnection { public static Connection connectDB(String DBName,String id,String p) { Connection con = null; String uri = "jdbc:mysql://localhost:3306/"+DBName+"?useSSL=true&characterEncoding=utf-8"; try{ Class.forName("com.mysql.jdbc.Driver");//加載JDBC-MySQL驅動 } catch(Exception e){} try{ con = DriverManager.getConnection(uri,id,p); //鏈接代碼 } catch(SQLException e){} return con; } }
這段代碼的功能是將mess表中的number字段R1001的height值減小n,並將減小的n增長到字段是R1002的height上。
Example11_8
import java.sql.*; public class Example11_8 { public static void main(String[] args) { Connection con =null; Statement sta = null; ResultSet rs; String SQL; try { Class.forName("org.apache.derby.jdbc.EmbeddedDriver");//加載驅動 } catch(Exception e) { System.out.println(e); return; } try { String uri ="jdbc:derby:students;create=true"; con=DriverManager.getConnection(uri); //鏈接數據庫 sta = con.createStatement(); } catch(Exception e) { System.out.println(e); return; } try { SQL = "create table chengji(name varchar(40),score float)"; sta.execute(SQL);//建立表 } catch(SQLException e) { //System.out.println("該表已經存在"); } SQL ="insert into chengji values"+ "('張三', 90),('李斯', 88),('劉二', 67)"; try { sta.execute(SQL); rs = sta.executeQuery("select * from chengji "); // 查詢表中的記錄 while(rs.next()) { String name=rs.getString(1); System.out.print(name+"\t"); float score=rs.getFloat(2); System.out.println(score); } con.close(); } catch(SQLException e) { System.out.println(e); } } }
這段代碼的功能是使用了Derby數據庫系統建立了名字是student的數據庫,並在數據庫中創建了chengji表