这只是一篇我自己学习java的流水账笔记,包含了以下内容,全是基础代码示例,希望对正在学习java的小伙伴有帮助
- java线程:Java Thread
- java网络编程:TCP/UDP programing : Say hello to server!
Java Thread
Creating thread
public class TestThread{
public static void main(String[] args){
Thread1 a = new Thread1();
Thread t = new Thread(a);
t.start();
for(int i= 1;i <= 1000;i++){
System.out.println("main : "+i);
}
System.out.println(t.isAlive());
}
}
class Thread1 implements Runnable{
public void run(){
for(int i= 1;i <= 1000;i++){
try{
System.out.println("Thread1 : "+i);
}catch
(InterruptedException e){e.printStackTrace();}
}
}
}
Testing join()
public class TestJoin{
public static void main(String[] args){
Runner1 r = new Runner1();
Thread t = new Thread(r);
t.start();
try{
t.join();
}catch(InterruptedException e){}
for(int i = 0;i<100;i++){
System.out.println("I am main");
}
}
}
class Runner1 implements Runnable{
public void run(){
for(int i = 0;i < 100;i++){
System.out.println("I am Runner1");
}
}
}
Testing priority()
public class TestPriority{
public static void main(String[] args){
R1 r1 = new R1();
R2 r2 = new R2();
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
//t2.setPriority(Thread.NORM_PRIORITY + 5);
t2.setPriority(Thread.NORM_PRIORITY - 4);
t1.start();t2.start();
}
}
class R1 implements Runnable{
public void run(){
for(int i = 0;i < 1000;i++){
System.out.println("=======I am R1");
}
}
}
class R2 implements Runnable{
public void run(){
for(int i =0;i < 1000;i++){
System.out.println("I am R2");
}
}
}
Testing yield()
public class TestYield{
public static void main(String[] args){
Runner2 r1 = new Runner2("t1=======");
Runner2 r2 = new Runner2("t2");
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();t2.start();
}
}
class Runner2 implements Runnable{
private String name;
Runner2(String name){
this.name = name;
}
public void run(){
for(int i = 0;i < 1000;i++){
System.out.println("I am "+ name +" : "+i);
if(i % 10 == 0){Thread.yield();}
}
}
}
Testing sleep()
import java.util.*;
public class TestSleep{
public static void main(String[] args){
Runner r = new Runner();
Thread t = new Thread(r);
t.start();
try {
Thread.sleep(10000);
}catch(InterruptedException e){e.printStackTrace();}
t.interrupt();
r.shutdown();
}
}
class Runner implements Runnable{
private boolean flag = true;
public void run(){
while(flag){
System.out.println("====="+new Date()+"=====");
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("interrupted");
//return;
}
}
}
public void shutdown(){
flag = false;
}
}
Testing synchronization
/*
key words:synchronized
*/
public class TestSynch1 implements Runnable{
Timer time = new Timer();
public static void main(String[] args){
TestSynch1 t = new TestSynch1();
Thread t1 = new Thread(t,"t1");
Thread t2 = new Thread(t,"t2");
t1.start();
t2.start();
}
public void run(){
time.add(Thread.currentThread().getName());
}
}
class Timer{
private static int num = 0;
public synchronized void add(String s){
//synchronized (this){
num++;
try{
Thread.sleep(1);//
}catch(InterruptedException e){}
System.out.println
(s+"是第"+num+"个调用该线程的!");
//}
}
}
public class TestSynch2 implements Runnable{
int b = 100;
public static void main(String[] args){
TestSynch2 test = new TestSynch2();
Thread t = new Thread(test);
t.start();
test.m2();
try{
Thread.sleep(100);
}catch(InterruptedException e){}
System.out.println(test.b);
}
public void run(){
m1();
}
public synchronized void m1(){
b = 1000;
try{
Thread.sleep(200);
}catch(InterruptedException e){}
System.out.println("m1 "+ b);
}
public synchronized void m2(){
/*
try{
Thread.sleep();
}catch(InterruptedException e){}*/
b = 2000;
System.out.println("m2 " +b);
}
}
Testing dead lock
public class TestDeadLock implements Runnable{
private int flag = 0;
static Object o1 = new Object();
static Object o2 = new Object();
public static void main(String[] args){
TestDeadLock deadLock1 = new TestDeadLock();
deadLock1.flag = 1;
TestDeadLock deadLock2 = new TestDeadLock();
deadLock2.flag = 2;
Thread t1 = new Thread(deadLock1);
Thread t2 = new Thread(deadLock2);
t1.start();t2.start();
}
public void run(){
System.out.println(flag);
if (flag == 1){
synchronized (o1) {
try{
Thread.sleep(500);
}catch(InterruptedException e){}
synchronized (o2){
System.out.println("t1");
}
}
}
if(flag == 2){
synchronized (o2) {
try{
Thread.sleep(500);
}catch(InterruptedException e){}
synchronized (o1){
System.out.println("t2");
}
}
}
}
}
Testing producer and consumer
public class Test1{
public static void main(String[] args){
/*
SyncStack ss = new SyncStack();
Wotou wt = new Wotou(0);
ss.push(wt);
Producer p = new Producer();
p.add();
Consumer c = new Consumer();
c.subtract();*/
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();t2.start();
}
}
class Wotou{
private int id;
Wotou(int id ){
this.id = id;
}
public String toString(){
return "wotou : " + id;
}
}
class SyncStack{
private int index;
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();
if ( index == arrwt.length ){}
arrwt[index] = wt;
index++;
System.out.println( "Producing " + index+" wt");
}
public synchronized Wotou pop(){
while(index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
//arrwt[index] = wt;
index--;
System.out.println( "Consuming " + index+" wt");
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);
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();
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
TCP/UDP programing : Say hello to server!
TCP Server
import java.net.*;
public class TestServerSocket {
public static void main(String[] args) throws Exception{
ServerSocket ss = new ServerSocket(6666);
while(true){
Socket s = ss.accept();
System.out.println("A client connect!");
}
}
}
TCP Client
import java.net.*;
import java.io.*;
public class TestSocket {
public static void main(String[] args) throws Exception {
Socket s = new Socket("45.32.18.35",6666);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Hello server");
System.out.println(s.getLocalPort());
dos.flush();dos.close();s.close();
}
}
TCP Server1
import java.net.*;
import java.io.*;
public class TestServer{
public static void main(String[] args){
try{
ServerSocket ss = new ServerSocket(6666);
while (true){
Socket s = ss.accept();
DataOutputStream dos = new DataOutputStream
( s.getOutputStream());
dos.writeUTF
("IP address: " + s.getInetAddress()+" "+"Port :" +s.getPort() );
dos.flush();
dos.close();
s.close();
}
}catch(IOException e){System.out.println("A error has occured!");}
}
}
TCP Client1
import java.io.*;
import java.net.*;
public class TestClient{
public static void main(String[] args){
try {
Socket s = new Socket("45.32.18.35",6666);
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readUTF());
dis.close();
s.close();
} catch (IOException e){
System.out.println("服务器连接失败!");
}
}
}
TCP Server2
import java.io.*;
import java.net.*;
public class TestServer1{
public static void main(String[] args){
String str = null;
DataInputStream dis = null;
DataOutputStream dos = null;
try{
ServerSocket ss = new ServerSocket(6666);
while(true) {
Socket s = ss.accept();
dis = new DataInputStream(s.getInputStream());
if ((str = dis.readUTF()) != null) {
System.out.println(str);
System.out.println("from host :"+ s.getInetAddress());
System.out.println("port : " +s.getPort());
System.out.println();
}
dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("hello client!");
dos.flush();
dos.close();
dis.close();
s.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
}
TCP Client2
import java.io.*;
import java.net.*;
public class TestSocket1{
public static void main(String[] args){
String str = null;
DataOutputStream dos = null;
DataInputStream dis = null;
try {
Socket s = new Socket("45.32.18.35",6666);
dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("hello server !");
dos.flush();
dis = new DataInputStream(s.getInputStream());
if ( ( str = dis.readUTF() ) != null ) {
System.out.println(str);
System.out.println(s.getInetAddress());
System.out.println(s.getPort());
System.out.println();
}
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
A peer-2-peer talking instance TCP server
import java.io.*;
import java.net.*;
public class TalkServer{
public static void main(String[] args){
String read = null;
String inWrite = null;
DataInputStream dis = null;
DataOutputStream dos = null;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
try {
ServerSocket ss = new ServerSocket(6666);
Socket s = ss.accept();
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
//read = dis.readUTF();
//inWrite = br.readLine();
System.out.println("Client say : " + dis.readUTF());
inWrite = br.readLine();
while( !inWrite.equalsIgnoreCase("exit") ) {
dos.writeUTF(inWrite);
dos.flush();
System.out.println("Server say : " + inWrite);
System.out.println("Client say : " + dis.readUTF());
inWrite = br.readLine();
}
dis.close();
dos.close();
s.close();
System.exit(-1);
}catch (IOException e) {e.printStackTrace();}
}
}
A peer-2-peer talking instance TCP client
import java.io.*;
import java.net.*;
public class TalkClient{
public static void main(String[] args){
String inWrite = null;
String read = null;
DataOutputStream dos = null;
DataInputStream dis = null;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
try {
Socket s = new Socket("127.0.0.1",6666);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
inWrite = br.readLine();
while( !inWrite.equalsIgnoreCase("exit") ){
dos.writeUTF(inWrite);
dos.flush();
System.out.println("Client say : " +inWrite);
System.out.println("Server say : " + dis.readUTF());
inWrite = br.readLine();
}
dos.close();
dis.close();
s.close();
System.exit(-1);
}catch(IOException e){e.printStackTrace();}
}
}
UDP Server
import java.net.*;
public class TestUDPServer1{
public static void main(String[] args){
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
try{
DatagramSocket ds = new DatagramSocket(6666);
while(true) {
ds.receive(dp);
System.out.println( new String(buf,0,dp.getLength()) );
}
}catch ( Exception e) {
e.printStackTrace();
}
}
}
UDP Client
import java.net.*;
public class TestUDPClient1{
public static void main(String[] args){
byte[] buf = (new String("Hello Server!")).getBytes();
DatagramPacket dp = new DatagramPacket
(buf,buf.length,new InetSocketAddress("127.0.0.1",6666));
try {
DatagramSocket ds = new DatagramSocket(7777);
ds.send(dp);
ds.close();
}catch ( Exception e) {
e.printStackTrace();
}
}
}
UDP Server1
import java.io.*;
import java.net.*;
public class TestUDPServer2{
public static void main(String[] args){
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket
(buf,buf.length);
try{
DatagramSocket ds = new DatagramSocket(6666);
while(true){
ds.receive(dp);
ByteArrayInputStream bais =
new ByteArrayInputStream(buf);
DataInputStream dis =
new DataInputStream(bais);
System.out.println(dis.readLong());
}
}catch(Exception e){e.printStackTrace();}
}
}
UDP Client1
import java.net.*;
import java.io.*;
public class TestUDPClient2{
public static void main(String[] args){
long n = 10000L;
byte[] buf = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
//
try{
dos.writeLong(n);
}catch (IOException e){e.printStackTrace();}
buf = baos.toByteArray();//important!
DatagramPacket dp = new DatagramPacket
(buf,buf.length,new InetSocketAddress("127.0.0.1",6666));
try {
DatagramSocket ds = new DatagramSocket(7777);
ds.send(dp);
ds.close();
}catch (Exception e){e.printStackTrace();}
try{
dos.close();
baos.close();
}catch(IOException e){e.printStackTrace();}
}
}
classes InetAddress & NetworkInterface
InetAddress
import java.net.*;
import java.io.*;
public class Test {
public static void main(String[] args) {
getByHost();
System.out.println();
getHostByIP();
System.out.println();
getAllIP();
System.out.println();
getLocal();
System.out.println();
createAddress();
System.out.println();
getByteIP();
System.out.println();
Reachable();
System.out.println();
addressEquals();
}
public static void getByHost(){
String hostName = "www.scriptwang.com";
try{
InetAddress address = InetAddress.getByName
(hostName);
System.out.println(address);
} catch (UnknownHostException ex) {
System.out.println("Can not find " + hostName);
}
}
public static void getHostByIP(){
String IP = "45.32.18.35";
try {
InetAddress address = InetAddress.getByName
(IP);
System.out.println(address.getHostName());
System.out.println(address.getCanonicalHostName());
} catch (UnknownHostException ex) {
System.out.println
("Can not find host name by " + IP);
}
}
public static void getAllIP() {
String hostName = "www.baidu.com";
try{
InetAddress[] addresses =
InetAddress.getAllByName(hostName);
for(InetAddress address : addresses) {
System.out.println(address);
}
}catch (UnknownHostException ex) {
System.out.println("Can not find " + hostName);
}
}
public static void getLocal() {
try {
InetAddress address = InetAddress.getLocalHost();
String str = address.getHostAddress();
System.out.println(address);
System.out.println(str);
} catch (UnknownHostException ex){
System.out.println
("Can not find this computer`s address!");
}
}
public static void createAddress(){
byte[] IP = {107,23,(byte)216,(byte)196};
try {
InetAddress address1 =
InetAddress.getByAddress(IP);
InetAddress address2 =
InetAddress.getByAddress("www.123.com",IP);
System.out.println(address1);
System.out.println(address2);
} catch (UnknownHostException ex) {
ex.printStackTrace();
}
}
public static void getByteIP() {
String host = "www.scriptwang.com";
try {
InetAddress address = InetAddress.getByName
(host);
byte[] IPArray = address.getAddress();
//print IPArray
for(byte ip : IPArray){
System.out.println(ip);
}
//check IPv4 or IPv6
if(IPArray.length == 4)
System.out.println("IPv4");
if(IPArray.length == 16)
System.out.println("IPv6");
} catch (UnknownHostException ex ) {
System.out.println();
}
}
public static void Reachable(){
String IP = "45.32.18.35";
try{
InetAddress address =
InetAddress.getByName(IP);
if(address.isReachable(500)){
System.out.println
(IP + " is reachable!");
}else{
System.out.println
(IP + " is not reachable!");
}
}catch(UnknownHostException ex){
System.out.println
("Can not find " + IP);
}catch ( IOException e){}
}
public static void addressEquals(){
//equals returns true only the same IP!
String host1 = "www.scriptwang.com";
String host2 = "img.scriptwang.com";
try{
InetAddress address1 =
InetAddress.getByName(host1);
InetAddress address2 =
InetAddress.getByName(host2);
if(address1.equals(address2)){
System.out.println
(address1 + " is the same as " + address2);
}else{
System.out.println
(address1 + " is the not same as " + address2);
}
}catch(UnknownHostException ex){
System.out.println
("Host lookup failed!");
}
}
}
import java.net.*;
public class TestIP{
public static void main(String[] args){
try {
InetAddress address =
InetAddress.getByName(args[0]);
if(address.isAnyLocalAddress()){
System.out.println
(address + " is a wildcard address!");
}
if(address.isLoopbackAddress()){
System.out.println
(address + " is a loop back address!");
}
if(address.isLinkLocalAddress()){
System.out.println
(address + " is a link-local address!");
}
if(address.isSiteLocalAddress()){
System.out.println
(address + " is a site-local address!");
}else{
System.out.println
(address + " is a global address!");
}
if(address.isMulticastAddress()){
if(address.isMCGlobal()){
System.out.println
(address + " is a global multicast address!");
}else if(address.isMCOrgLocal()){
System.out.println
(address + " is an organization multicast address!");
}else if(address.isMCSiteLocal()){
System.out.println
(address + " is a site multicast address!");
}else if(address.isMCLinkLocal()){
System.out.println
(address + " is a subnet multicast address!");
}else if(address.isMCNodeLocal()){
System.out.println
(address + " is an interface-local multicast address!");
}else{
System.out.println
(address + " is a unknown multicast address type!");
}
}else{
System.out.println
(address + " is a unicast address!");
}
} catch (UnknownHostException ex){
System.out.println
("Could not resolve " + args[0]);
}
}
}
NetworkInterface
import java.net.*;
import java.util.*;
public class TestNetworkInterface{
public static void main(String[] args){
test1();
System.out.println();
test2();
System.out.println();
//InterfaceLister();
System.out.println();
interfaceIPLister();
}
public static void test1(){
try{
NetworkInterface ni =
NetworkInterface.getByName
("eth0");
System.out.println
(ni);
}catch(SocketException e){
}
}
public static void test2(){
String IP = "127.0.0.1";
try {
InetAddress address =
InetAddress.getByName(IP);
NetworkInterface ni =
NetworkInterface.getByInetAddress
(address);
System.out.println(ni);
}catch(SocketException e){
System.err.println();
}catch(UnknownHostException e1){
System.err.println();
}
}
public static void InterfaceLister(){
try {
Enumeration<NetworkInterface> interfaces =
NetworkInterface.getNetworkInterfaces();
while(interfaces.hasMoreElements()){
NetworkInterface ni =
interfaces.nextElement();
System.out.println(ni);
}
}catch(SocketException e){
}
}
public static void interfaceIPLister(){
try{
Enumeration<NetworkInterface> interfaces =
NetworkInterface.getNetworkInterfaces();
while(interfaces.hasMoreElements()){
NetworkInterface ni =
interfaces.nextElement();
System.out.println(ni);
Enumeration e = ni.getInetAddresses();
while(e.hasMoreElements()){
System.out.println
(ni.getName()+" -->>InetAddress : "+e.nextElement());
}
System.out.println();
}
}catch(SocketException e){}
}
}
SpamCheck
import java.net.*;
public class SpamCheck{
public static final String BLACKHOLE =
"sbl.spamhaus.org";
public static void main(String[] args){
for(String arg:args){
if(isSpammer(arg)){
System.out.println(arg + " is a spammer!");
}else{
System.out.println(arg + " is not a spammer!");
}
}
}
public static boolean isSpammer(String IP){
try{
InetAddress address =
InetAddress.getByName(IP);
byte[] ipArray = address.getAddress();
String query = BLACKHOLE;
for(byte b : ipArray){
int unsignedByte =
b < 0 ? b + 256 : b;
query = unsignedByte + "." + query;
//System.out.println(query);
}
InetAddress.getByName(query);
return true;
}catch(UnknownHostException e){
return false;
}
}
}
WebLog
import java.io.*;
import java.net.*;
public class WebLog{
public static void main(String[] args){
try(FileInputStream fis = new FileInputStream(args[0]);
Reader r = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(r);){
for(String entry = br.readLine();
entry!=null;entry = br.readLine()){
int index = entry.indexOf(" ");
String IP = entry.substring(0,index);
String rest = entry.substring(index);
try{
InetAddress address =
InetAddress.getByName(IP);
String host = address.getHostName();
System.out.println
(host +" "+rest);
}catch(UnknownHostException e){
}
}
}catch(IOException e){
}
}
}
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.*;
public class WebLogThread{
private final static int NUM_THREADS = 4;
public static void main(String[] args)throws IOException{
ExecutorService executor =
Executors.newFixedThreadPool(NUM_THREADS);
Queue<LogEntry> results = new LinkedList<LogEntry>();
try( BufferedReader br =
new BufferedReader(
new InputStreamReader(
new FileInputStream(args[0]), "UTF-8"))){
for(String entry = br.readLine();
entry != null;
entry = br.readLine()){
LookupTask task = new LookupTask(entry);
Future<String> future = executor.submit(task);
LogEntry result = new LogEntry(entry,future);
results.add(result);
}
}
for(LogEntry result : results){
try{
System.out.println(result.future.get());
}catch( InterruptedException | ExecutionException ex ){
System.out.println(result.original);
}
}
}
private static class LogEntry{
String original;
Future<String> future;
LogEntry(String original,Future<String> future){
this.original = original;
this.future = future;
}
}
}
class LookupTask implements Callable<String>{
private String line;
public LookupTask(String line){
this.line = line;
}
//@override
public String call(){
try{
int index = line.indexOf(" ");
String IP = line.substring(0,index);
String rest = line.substring(index);
String hostName =
InetAddress.getByName(IP).getHostName();
return hostName + " " + rest;
}catch(Exception e){}
return line;
}
}
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/10087.html