代码收藏

-----JDBC--------
package com.terac.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DBTest {
public static void main(String[] args) {
try {
String user = "user";
String password = "password";
String driver = "COM.ibm.db2.jdbc.net.DB2Driver";
//"oracle.jdbc.driver.OracleDriver";
//"com.mysql.jdbc.Driver";
//"org.postgresql.Driver";
String url = "jdbc:db2://localhost/a";
//"jdbc:oracle:thin:@localhost:1521:a";
//"jdbc:mysql://localhost/a";
//"jdbc:postgresql://localhost:5740/a";
String sql = "SELECT current timestamp FROM sysibm.sysdummy1";
//"SELECT sysdate FROM dual";
//"SELECT now()";
//"SELECT current_timestamp";
Class.forName(driver).newInstance();
Connection c = DriverManager.getConnection(url, user, password);
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
------------
 Class.forName("com.mysql.jdbc.Driver").newInstance();
     con=DriverManager.getConnection("jdbc:mysql://192.168.0.73:3306/chancedb?user=root&password=1&useUnicode=true&characterEncoding=GB2312");
     stmt=con.createStatement();
     String upd="INSERT INTO Sample_test(employee_id, last_name, first_name, birth, sex, email) VALUES ("+employee_id+",'"+last_name+"','"+first_name+"','"+birth+"','"+sex+"','"+email+"')";
     stmt.executeUpdate(upd);
     stmt1=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
     String query="SELECT * FROM Sample_test";
     rs=stmt1.executeQuery(query);
     rs.last();
     new_last_name=rs.getString("last_name");
     new_first_name=rs.getString("first_name");
     stmt.close();
     stmt1.close();
     con.close();
   }
   catch(SQLException sqle)
   {
    out.println("sqle=" +sqle);
   }
   finally
   {
    try{
     if(con !=null)
     {
      con.close();
      
     }
     
    }
    catch(SQLException sqle)
    {
     out.println("sqle="+sqle);
    }
   }
--------------事务处理------------
try{

 conn=DriverManager.getConnection("..."); //链接数据库 

 conn.setAutoCommit(false);//禁止自动提交事务 
 stmt = conn.Create....
 String sql1 = "update useraccount set monery=monery-1000 where name='usename'";
 String sql2 = "update sysaccount set monery=monery+1000 where name='sysname'"; 
 stmt=conn.createStatement(); 
 stmt.executeUpdate(sql1); 
 stmt.executeUpdate(sql2); 

 conn.commit(); //统一提交。

 }catch(SQLException e){ 
  conn.rollback(); //倘若其中一项sql操作失败,就不会执行commit()方法,而是产生相应的sqlexception,此时就可以捕获 异常代码块中调用rollback()方法撤消事务。 
  e.printStackTrace(); 
 } 
 finally{ 
  if(stmt!=null){ 
   stmt.close(); 
  } 
  if(conn!=null){ 
   stmt.close(); 
  } 
 }
------死锁例子-----
public class TestDeadLock implements Runnable {
	public int flag = 1;
	static Object o1 = new Object(), o2 = new Object();
	public void run() {
System.out.println("flag=" + flag);
		if(flag == 1) {
			synchronized(o1) {
				try {
					Thread.sleep(500);
				} catch (Exception e) {
					e.printStackTrace();
				}
				synchronized(o2) {
					System.out.println("1");	
				}
			}
		}
		if(flag == 0) {
			synchronized(o2) {
				try {
					Thread.sleep(500);
				} catch (Exception e) {
					e.printStackTrace();
				}
				synchronized(o1) {
					System.out.println("0");
				}
			}
		}
	}	
	
	public static void main(String[] args) {
		TestDeadLock td1 = new TestDeadLock();
		TestDeadLock td2 = new TestDeadLock();
		td1.flag = 1;
		td2.flag = 0;
		Thread t1 = new Thread(td1);
		Thread t2 = new Thread(td2);
		t1.start();
		t2.start();
		
	}
}
--------m2输出为1000,锁定的是方法,不是资源
public class TT implements Runnable {
	int b = 100;
	
	public synchronized void m1() throws Exception{
		b = 1000;
		Thread.sleep(5000);
		System.out.println("b = " + b);
	}
	
	public void m2() {
		System.out.println(b);
	}
	
	public void run() {
		try {
			m1();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws Exception {
		TT tt = new TT();
		Thread t = new Thread(tt);
		t.start();
		
		Thread.sleep(1000);
		tt.m2();
	}
}
-----以下输出b=2000(m1输出);
public class TT implements Runnable {
	int b = 100;
	
	public synchronized void m1() throws Exception{
		b = 1000;
		Thread.sleep(5000);
		System.out.println("b = " + b);
	}
	
	public  void m2() throws Exception {
		Thread.sleep(2500);
		b = 2000;
	}
	
	public void run() {
		try {
			m1();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws Exception {
		TT tt = new TT();
		Thread t = new Thread(tt);
		t.start();
		
		tt.m2();
	}
}
-----给m2加锁b=1000(m1输出),对访问资源的所有方法都得加锁。m2必须得到锁才能执行
	可考虑隐式锁
public class TT implements Runnable {
	int b = 100;
	
	public synchronized void m1() throws Exception{
		b = 1000;
		Thread.sleep(5000);
		System.out.println("b = " + b);
	}
	
	public synchronized void m2() throws Exception {
		Thread.sleep(2500);
		b = 2000;
		System.out.println(b);//2000
	}
	
	public void run() {
		try {
			m1();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws Exception {
		TT tt = new TT();
		Thread t = new Thread(tt);
		t.start();
		
		tt.m2();
	}
}
--------------生产者消费者问题---------------------
public class ProducerConsumer {
	public static void main(String[] args) {
		SyncStack ss = new SyncStack();
		Producer p = new Producer(ss);
		Consumer c = new Consumer(ss);
		new Thread(p).start();
		new Thread(p).start();
		new Thread(p).start();
		new Thread(c).start();
	}
}

class WoTou {
	int id; 
	WoTou(int id) {
		this.id = id;
	}
	public String toString() {
		return "WoTou : " + id;
	}
}

class SyncStack {
	int index = 0;
	WoTou[] arrWT = new WoTou[6];
	
	public synchronized void push(WoTou wt) {
		while(index == arrWT.length) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();		
		arrWT[index] = wt;
		index ++;
	}
	
	public synchronized WoTou pop() {
		while(index == 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();
		index--;
		return arrWT[index];
	}
}

class Producer implements Runnable {
	SyncStack ss = null;
	Producer(SyncStack ss) {
		this.ss = ss;
	}
	
	public void run() {
		for(int i=0; i<20; i++) {
			WoTou wt = new WoTou(i);
			ss.push(wt);
System.out.println("生产了:" + wt);
			try {
				Thread.sleep((int)(Math.random() * 200));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}			
		}
	}
}

class Consumer implements Runnable {
	SyncStack ss = null;
	Consumer(SyncStack ss) {
		this.ss = ss;
	}
	
	public void run() {
		for(int i=0; i<20; i++) {
			WoTou wt = ss.pop();
System.out.println("消费了: " + wt);
			try {
				Thread.sleep((int)(Math.random() * 1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}			
		}
	}
}
----------------IO----------------------
import java.io.*;
public class TestTransForm2 {
  public static void main(String args[]) {
    InputStreamReader isr = 
            new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    String s = null;
    try {
      s = br.readLine();
      while(s!=null){
        if(s.equalsIgnoreCase("exit")) break;
        System.out.println(s.toUpperCase());
        s = br.readLine();
      }
      br.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
} //阻塞
--------------
import java.io.*;
public class TestDataStream {
  public static void main(String[] args) {
    ByteArrayOutputStream baos = 
                        new ByteArrayOutputStream(); 
    DataOutputStream dos = 
                        new DataOutputStream(baos);
    try {
      dos.writeDouble(Math.random());
      dos.writeBoolean(true);
      ByteArrayInputStream bais = 
          new ByteArrayInputStream(baos.toByteArray());
      System.out.println(bais.available());
      DataInputStream dis = new DataInputStream(bais);
      System.out.println(dis.readDouble());
      System.out.println(dis.readBoolean());
      dos.close();  dis.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
-----------编译错误---------j无法传进去
class Outer {
	public static Object add(int j) {
		return new Object() {
			private int i = 11;
			{
				i += j;
				System.out.println("i = "+i);
				
			}
		};
	}
}
------------Socket网络编程--------------------
import java.io.*; 
import java.net.*;
public class TestSockServer {
  public static void main(String[] args) {
    InputStream in = null; 
    OutputStream out = null;
    try {
      ServerSocket ss = new ServerSocket(5888);
      Socket socket = ss.accept();
      in = socket.getInputStream(); 
      out = socket.getOutputStream();
      DataOutputStream dos = new DataOutputStream(out);
      DataInputStream dis = new DataInputStream(in);
      String s = null;
      if((s=dis.readUTF())!=null) {
	      System.out.println(s);
	      System.out.println("from: "+socket.getInetAddress());
	      System.out.println("Port: "+socket.getPort());
	    }
      dos.writeUTF("hi,hello"); 
      dis.close();
      dos.close();
      socket.close();
    } catch (IOException e) {e.printStackTrace();}
  }
}

import java.net.*;
import java.io.*;
public class TestSockClient {
  public static void main(String[] args) {
    InputStream is = null; OutputStream os = null;
    try {
      Socket socket = new Socket("localhost",5888);
      is = socket.getInputStream();
      os = socket.getOutputStream();
      DataInputStream dis = new DataInputStream(is);
      DataOutputStream dos = new DataOutputStream(os);
      dos.writeUTF("hey"); 
      String s = null;
      if((s=dis.readUTF())!=null);
      	System.out.println(s); 
      dos.close();
      dis.close();
      socket.close();
    } catch (UnknownHostException e) {
       e.printStackTrace();
    } catch (IOException e) {e.printStackTrace();}
  }
}
-----------UDP-----------
import java.net.*;
import java.io.*;

public class TestUDPServer
{
	public static void main(String args[]) throws Exception
	{
		byte buf[] = new byte[1024];
		DatagramPacket dp = new DatagramPacket(buf, buf.length);
		DatagramSocket ds = new DatagramSocket(5678);
		while(true)
		{
			ds.receive(dp);
			ByteArrayInputStream bais = new ByteArrayInputStream(buf);
			DataInputStream dis = new DataInputStream(bais);
			System.out.println(dis.readLong());
		}
	}
}

import java.net.*;
import java.io.*;

public class TestUDPClient
{
	public static void main(String args[]) throws Exception
	{
		long n = 10000L;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		dos.writeLong(n);
		
		byte[] buf = baos.toByteArray();
System.out.println(buf.length);
		
		DatagramPacket dp = new DatagramPacket(buf, buf.length, 
 	new InetSocketAddress("127.0.0.1", 5678));
		DatagramSocket ds = new DatagramSocket(9999);
		ds.send(dp);
		ds.close();
		
	}
}
-------------------
public class ThreadTest {
	private int j;
	
	public static void main(String[] args) {
		
		ThreadTest tt = new ThreadTest();
		Increment inc = tt.new Increment();
		Decement dec = tt.new Decement();
		for(int i=0;i<2;i++) {
			Thread t = new Thread(inc);
			t.start();
			t = new Thread(dec);
			t.start();
		}
	}
	private synchronized void inc() {
		j++;
		System.out.println(Thread.currentThread().getName()+"-inc "+j);
	}
	private synchronized void dec() {
		j--;
		System.out.println(Thread.currentThread().getName()+"-dec "+j);
	}
	class Increment implements Runnable {
		public void run() {
			for(int i = 0;i<100; i++) {
				inc();
				System.out.println(Thread.currentThread().getName()+"No."+i);
			}
		}
	}
	class Decement implements Runnable {
		public void run() {
			for(int i = 0;i<100; i++) {
				dec();
				System.out.println(Thread.currentThread().getName()+"No."+i);
			}
		}
	}
}
------------0626打印MARK----
/** 
用1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列, 
如:512234、412345等,要求: "4 "不能在第三位, "3 "与 "5 "不能相连. 
*/ 

import java.util.Iterator;   
import java.util.TreeSet;   
  
/**  
 * time 2011/03/18  
 * @author liuxingyu  
 *  
 */  
public class Travel_Graph {   
  
    private String[] b = new String[]{"1","2","2","3","4","5"};   
    private int n = b.length;   
    private boolean[] visited = new boolean[n];   
    private int[][] a = new int[n][n];   
    private String result ="";   
    private TreeSet<String>  TreeSet = new  TreeSet<String>();   
       
    private void start(){   
        for(int i = 0 ;i<n;i++){   
            for(int j=0; j<n ;j++){   
                if(i==j){   
                    a[i][j]=0;   
                }else{   
                    a[i][j]=1;   
                }   
            }   
        }   
        a[3][5]=0;   
        a[5][3]=0;   
        for(int i =0;i<n;i++){   
            this.depthFirstSearch(i);   
        }   
        Iterator<String> it = TreeSet.iterator();   
        while(it.hasNext()){   
            String string = (String)it.next();   
            if(string.indexOf("4")!=2){   
                System.out.println(string);   
            }   
        }   
           
    }   
       
    private void depthFirstSearch(int startIndex) {   
        visited[startIndex]=true;   
        result = result+b[startIndex];   
        if(result.length()==n){   
            TreeSet.add(result);   
        }   
        for(int j=0;j<n;j++){   
            if(a[startIndex][j]==1&& visited[j]==false){   
                depthFirstSearch(j);   
            }else{   
                continue;   
            }   
        }   
        result = result.substring(0,result.length()-1);   
        visited[startIndex]= false;   
    }   
  
    public static void main(String[] args) {   
        new Travel_Graph().start();   
    }   
  
}  



你可能感兴趣的:(thread,exception,String,null,Class,import)