提交 687d35e2 编写于 作者: 武汉红喜's avatar 武汉红喜

update package name

上级 1ac418cf
package com.itlong.whatsmars.base;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by shenhongxi on 15/7/28.
*/
public class MapTest {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<String, Object>();
map = new LinkedHashMap<String, Object>();
map = new WeakHashMap<String, Object>();
Set<String> set = new LinkedHashSet<String>();
set = new TreeSet();
map = new TreeMap<String, Object>();
Iterator<String> iter = set.iterator();
List<String> list = new ArrayList<String>();
iter = list.iterator();
list = new LinkedList<String>();
Random r = new Random();
int a = r.nextInt();
System.out.println(a);
map = new ConcurrentHashMap<String, Object>();
}
}
package com.itlong.whatsmars.base;
import java.io.*;
import java.lang.reflect.Constructor;
/**
* Created by shenhongxi on 15/7/23.
*/
public class Singleton implements Serializable {
private static final Singleton instance = new Singleton();
private Singleton() {
//避免反射机制,导致的多例问题,通过反射机制仍然可以对私有构造函数进行操作 ?
if (instance != null) {
throw new RuntimeException("instance != null");
}
}
public static Singleton getInstance() {
return instance;
}
private void writeObject(ObjectOutputStream out) {
System.out.println("write object");
}
private void readObject(ObjectInputStream in) {
System.out.println("read object");
}
public Object writeReplace() {
System.out.println("write replace");
return instance;
}
public Object readResolve() {
System.out.println("read resolve");
return instance;
}
public static void main(String[] args) throws Exception {
String filePath = "/Users/javahongxi/xx.txt";
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath));
out.writeObject(getInstance());
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath));
Singleton o = (Singleton) in.readObject();
System.out.println(instance.hashCode());
System.out.println(o.hashCode());
System.out.println(o == instance);
System.out.println();
Constructor[] constructors = Singleton.class.getDeclaredConstructors();
Constructor<Singleton> c = constructors[0];
c.setAccessible(true);
Singleton o2 = c.newInstance();
System.out.println("HashCode 1 : " + getInstance().hashCode());
System.out.println("HashCode 2 : " + o2.hashCode());
System.out.println("Equal : " + (getInstance() == o2));//打破单例
}
}
package com.itlong.whatsmars.base.collection;
/**
* Created by shenhongxi on 2016/6/14.
*/
public class Point {
private float x;
private float y;
public Point(float x, float y){
setLocation(x, y);
}
public void setLocation(float x, float y){
this.x = x;
this.y = y;
}
public float getX(){
return x;
}
public float getY(){
return y;
}
}
package com.itlong.whatsmars.base.dp.factory;
public class Car implements Moveable {
private static Car car = new Car();//单例
//private static List<Car> cars = new ArrayList<Car>();//多例
/*private Car() {}
public static Car getInstance() {
return car;
}*/
public Car() {}
public void run() {
System.out.println("car running...");
}
}
package com.itlong.whatsmars.base.dp.factory;
public abstract class VehicleFactory {
abstract Moveable create();
}
package com.itlong.whatsmars.base.dp.factory.abstractfac;
public class DefaultFactory extends AbstractFactory {
@Override
Food createFood() {
// TODO Auto-generated method stub
return new Apple();
}
@Override
Vehicle createVehicle() {
// TODO Auto-generated method stub
return new Car();
}
@Override
Weapon createWeapon() {
// TODO Auto-generated method stub
return new AK47();
}
}
package com.itlong.whatsmars.base.dp.filter;
public class MsgProcessor {
private String msg;
//Filter[] filters = {new HTMLFilter(), new SesitiveFilter(), new FaceFilter()};
FilterChain fc;
public FilterChain getFc() {
return fc;
}
public void setFc(FilterChain fc) {
this.fc = fc;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String process() {
return fc.doFilter(msg);
}
}
package com.itlong.whatsmars.base.dp.filter;
public class SensitiveFilter implements Filter {
@Override
public String doFilter(String str) {
//process the sensitive words
String r = str.replace("被就业", "就业")
.replace("敏感", "");
return r;
}
}
package com.itlong.whatsmars.base.dp.filter.web;
public interface Filter {
void doFilter(Request request, Response response, FilterChain fc);
}
package com.itlong.whatsmars.base.dp.iterator;
public class ArrayList implements Collection {
Object[] objects = new Object[10];
int index = 0;
public void add(Object o) {
if(index == objects.length) {
Object[] newObjects = new Object[objects.length * 2];
System.arraycopy(objects, 0, newObjects, 0, objects.length);
objects = newObjects;
}
objects[index] = o;
index ++;
}
public int size() {
return index;
}
public Iterator iterator() {
return new ArrayListIterator();
}
private class ArrayListIterator implements Iterator {
private int currentIndex = 0;
@Override
public boolean hasNext() {
if(currentIndex >= index) return false;
else return true;
}
@Override
public Object next() {
Object o = objects[currentIndex];
currentIndex ++;
return o;
}
}
}
package com.itlong.whatsmars.base.dp.iterator;
public interface Collection {
void add(Object o);
int size();
Iterator iterator();
}
package com.itlong.whatsmars.base.dp.iterator;
public class Node {
public Node(Object data, Node next) {
super();
this.data = data;
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
private Object data;
private Node next;
}
package com.itlong.whatsmars.base.dp.proxy;
public interface Moveable {
void move();
}
package com.itlong.whatsmars.base.nio;// $Id$
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class FastCopyFile
{
static public void main( String args[] ) throws Exception {
if (args.length<2) {
System.err.println( "Usage: java FastCopyFile infile outfile" );
System.exit( 1 );
}
String infile = args[0];
String outfile = args[1];
FileInputStream fin = new FileInputStream( infile );
FileOutputStream fout = new FileOutputStream( outfile );
FileChannel fcin = fin.getChannel();
FileChannel fcout = fout.getChannel();
ByteBuffer buffer = ByteBuffer.allocateDirect( 1024 );
while (true) {
buffer.clear();
int r = fcin.read( buffer );
if (r==-1) {
break;
}
buffer.flip();
fcout.write( buffer );
}
}
}
package com.itlong.whatsmars.base.nio;// $Id$
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class UseFileLocks
{
static private final int start = 10;
static private final int end = 20;
static public void main( String args[] ) throws Exception {
// Get file channel
RandomAccessFile raf = new RandomAccessFile( "usefilelocks.txt", "rw" );
FileChannel fc = raf.getChannel();
// Get lock
System.out.println( "trying to get lock" );
FileLock lock = fc.lock( start, end, false );
System.out.println( "got lock!" );
// Pause
System.out.println( "pausing" );
try { Thread.sleep( 3000 ); } catch( InterruptedException ie ) {}
// Release lock
System.out.println( "going to release lock" );
lock.release();
System.out.println( "released lock" );
raf.close();
}
}
package com.itlong.whatsmars.base.nio;// $Id$
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
public class UseScatterGather
{
static private final int firstHeaderLength = 2;
static private final int secondHeaderLength = 4;
static private final int bodyLength = 6;
static public void main( String args[] ) throws Exception {
if (args.length!=1) {
System.err.println( "Usage: java UseScatterGather port" );
System.exit( 1 );
}
int port = Integer.parseInt( args[0] );
ServerSocketChannel ssc = ServerSocketChannel.open();
InetSocketAddress address = new InetSocketAddress( port );
ssc.socket().bind( address );
int messageLength =
firstHeaderLength + secondHeaderLength + bodyLength;
ByteBuffer buffers[] = new ByteBuffer[3];
buffers[0] = ByteBuffer.allocate( firstHeaderLength );
buffers[1] = ByteBuffer.allocate( secondHeaderLength );
buffers[2] = ByteBuffer.allocate( bodyLength );
SocketChannel sc = ssc.accept();
while (true) {
// Scatter-read into buffers
int bytesRead = 0;
while (bytesRead < messageLength) {
long r = sc.read( buffers );
bytesRead += r;
System.out.println( "r "+r );
for (int i=0; i<buffers.length; ++i) {
ByteBuffer bb = buffers[i];
System.out.println( "b "+i+" "+bb.position()+" "+bb.limit() );
}
}
// Process message here
// Flip buffers
for (int i=0; i<buffers.length; ++i) {
ByteBuffer bb = buffers[i];
bb.flip();
}
// Scatter-write back out
long bytesWritten = 0;
while (bytesWritten<messageLength) {
long r = sc.write( buffers );
bytesWritten += r;
}
// Clear buffers
for (int i=0; i<buffers.length; ++i) {
ByteBuffer bb = buffers[i];
bb.clear();
}
System.out.println( bytesRead+" "+bytesWritten+" "+messageLength );
}
}
}
package com.itlong.whatsmars.base.nio.qing;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
public class Packet implements Serializable {
/**
*
*/
private static final long serialVersionUID = 7719389291885063462L;
private ByteBuffer buffer;
private static Charset charset = Charset.defaultCharset();
private Packet(ByteBuffer buffer){
this.buffer = buffer;
}
public String getDataAsString(){
return charset.decode(buffer).toString();
}
public byte[] getData(){
return buffer.array();
}
public ByteBuffer getBuffer(){
return this.buffer;
}
public static Packet wrap(ByteBuffer buffer){
return new Packet(buffer);
}
public static Packet wrap(String data){
ByteBuffer source = charset.encode(data);
return new Packet(source);
}
}
package com.itlong.whatsmars.base.socket;
import java.io.*;
import java.net.*;
public class TCPClientModel {
public static void main(String[] args) {
new TCPClientModel().connect();
}
public void connect() {
@SuppressWarnings("unused")
boolean started = false;
Socket s = null;
DataOutputStream dos = null;
try {
s = new Socket("127.0.0.1", 5555);
dos = new DataOutputStream(s.getOutputStream());
started = true;
System.out.println("Yeah, I connected");
Thread.sleep(3000);
dos.writeUTF("Happy");
dos.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (dos != null) dos.close();
if (s != null) s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.itlong.whatsmars.base.thread;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
//不能改动此Test类
public class CopyOnWriteArrayListTest extends Thread {
private TestDo testDo;
private String key;
private String value;
public CopyOnWriteArrayListTest(String key, String key2, String value) {
this.testDo = TestDo.getInstance();
/*
* 常量"1"和"1"是同一个对象,下面这行代码就是要用"1"+""的方式产生新的对象,
* 以实现内容没有改变,仍然相等(都还为"1"),但对象却不再是同一个的效果
*/
this.key = key + key2;
/*
* a = "1"+""; b = "1"+""
*/
this.value = value;
}
public static void main(String[] args) throws InterruptedException {
CopyOnWriteArrayListTest a = new CopyOnWriteArrayListTest("1", "", "1");
CopyOnWriteArrayListTest b = new CopyOnWriteArrayListTest("1", "", "2");
CopyOnWriteArrayListTest c = new CopyOnWriteArrayListTest("3", "", "3");
CopyOnWriteArrayListTest d = new CopyOnWriteArrayListTest("4", "", "4");
System.out.println("begin:" + (System.currentTimeMillis() / 1000));
a.start();
b.start();
c.start();
d.start();
}
public void run() {
testDo.doSome(key, value);
}
}
class TestDo {
private TestDo() {
}
private static TestDo _instance = new TestDo();
public static TestDo getInstance() {
return _instance;
}
// private ArrayList keys = new ArrayList();
private CopyOnWriteArrayList<Object> keys = new CopyOnWriteArrayList<Object>();
public void doSome(Object key, String value) {
Object o = key;
if (!keys.contains(o)) {
keys.add(o);
} else {
for (Iterator<Object> iter = keys.iterator(); iter.hasNext();) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
Object oo = iter.next();
if (oo.equals(o)) {
o = oo;
break;
}
}
}
synchronized (o)
// 以大括号内的是需要局部同步的代码,不能改动!
{
try {
Thread.sleep(1000);
System.out.println(key + ":" + value + ":"
+ (System.currentTimeMillis() / 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.itlong.whatsmars.base.thread;
public class MultiThreadShareData {
@SuppressWarnings("unused")
private static ShareData1 data1 = new ShareData1();
public static void main(String[] args) {
ShareData1 data2 = new ShareData1();
new Thread(new MyRunnable1(data2)).start();
new Thread(new MyRunnable2(data2)).start();
final ShareData1 data1 = new ShareData1();
new Thread(new Runnable(){
@Override
public void run() {
data1.decrement();
}
}).start();
new Thread(new Runnable(){
@Override
public void run() {
data1.increment();
}
}).start();
}
}
class MyRunnable1 implements Runnable{
private ShareData1 data1;
public MyRunnable1(ShareData1 data1){
this.data1 = data1;
}
public void run() {
data1.decrement();
}
}
class MyRunnable2 implements Runnable{
private ShareData1 data1;
public MyRunnable2(ShareData1 data1){
this.data1 = data1;
}
public void run() {
data1.increment();
}
}
class ShareData1 /*implements Runnable*/{
/* private int count = 100;
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
count--;
}
}*/
@SuppressWarnings("unused")
private int j = 0;
public synchronized void increment(){
j++;
}
public synchronized void decrement(){
j--;
}
}
\ No newline at end of file
package com.itlong.whatsmars.base.thread;
import java.util.Random;
public class ThreadLocalTest {
private static ThreadLocal<Integer> x = new ThreadLocal<Integer>();
//private static ThreadLocal<MyThreadScopeData> myThreadScopeData = new ThreadLocal<MyThreadScopeData>();
public static void main(String[] args) {
for(int i=0;i<2;i++){
new Thread(new Runnable(){
@Override
public void run() {
int data = new Random().nextInt();
System.out.println(Thread.currentThread().getName()
+ " has put data :" + data);
x.set(data);
/* MyThreadScopeData myData = new MyThreadScopeData();
myData.setName("name" + data);
myData.setAge(data);
myThreadScopeData.set(myData);*/
MyThreadScopeData.getThreadInstance().setName("name" + data);
MyThreadScopeData.getThreadInstance().setAge(data);
new A().get();
new B().get();
}
}).start();
}
}
static class A{
public void get(){
int data = x.get();
System.out.println("A from " + Thread.currentThread().getName()
+ " get data :" + data);
/* MyThreadScopeData myData = myThreadScopeData.get();;
System.out.println("A from " + Thread.currentThread().getName()
+ " getMyData: " + myData.getName() + "," +
myData.getAge());*/
MyThreadScopeData myData = MyThreadScopeData.getThreadInstance();
System.out.println("A from " + Thread.currentThread().getName()
+ " getMyData: " + myData.getName() + "," +
myData.getAge());
}
}
static class B{
public void get(){
int data = x.get();
System.out.println("B from " + Thread.currentThread().getName()
+ " get data :" + data);
MyThreadScopeData myData = MyThreadScopeData.getThreadInstance();
System.out.println("B from " + Thread.currentThread().getName()
+ " getMyData: " + myData.getName() + "," +
myData.getAge());
}
}
}
class MyThreadScopeData{
private MyThreadScopeData(){}
public static /*synchronized*/ MyThreadScopeData getThreadInstance(){
MyThreadScopeData instance = map.get();
if(instance == null){
instance = new MyThreadScopeData();
map.set(instance);
}
return instance;
}
//private static MyThreadScopeData instance = null;//new MyThreadScopeData();
private static ThreadLocal<MyThreadScopeData> map = new ThreadLocal<MyThreadScopeData>();
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.itlong.whatsmars.base.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreeConditionCommunication {
/**
* @param args
*/
public static void main(String[] args) {
final Business business = new Business();
new Thread(
new Runnable() {
@Override
public void run() {
for(int i=1;i<=50;i++){
business.sub2(i);
}
}
}
).start();
new Thread(
new Runnable() {
@Override
public void run() {
for(int i=1;i<=50;i++){
business.sub3(i);
}
}
}
).start();
for(int i=1;i<=50;i++){
business.main(i);
}
}
static class Business {
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
private int shouldSub = 1;
public void sub2(int i){
lock.lock();
try{
while(shouldSub != 2){
try {
condition2.await();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=10;j++){
System.out.println("sub2 thread sequence of " + j + ",loop of " + i);
}
shouldSub = 3;
condition3.signal();
}finally{
lock.unlock();
}
}
public void sub3(int i){
lock.lock();
try{
while(shouldSub != 3){
try {
condition3.await();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=20;j++){
System.out.println("sub3 thread sequence of " + j + ",loop of " + i);
}
shouldSub = 1;
condition1.signal();
}finally{
lock.unlock();
}
}
public void main(int i){
lock.lock();
try{
while(shouldSub != 1){
try {
condition1.await();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=100;j++){
System.out.println("main thread sequence of " + j + ",loop of " + i);
}
shouldSub = 2;
condition2.signal();
}finally{
lock.unlock();
}
}
}
}
package com.itlong.whatsmars.base.thread.base;
public class BallThread extends Thread {
public static void main(String[] args) {
BallThread t = new BallThread();
t.start();
}
public void run() {
for (int t = 1; t <= 10; t++) {
double y = 9.8 * t * t / 2;
y /= 100;
String ball = " o";
for (int i = 0; i < Math.round(y); i++) {
System.out.println();
}
System.out.println(ball);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
package com.whatsmars.base;
/**
* Created by shenhongxi on 2017/11/17.
*/
public class CodeBlockTest {
int a = 110;
static int b = 112;
// static CodeBlockTest instance = new CodeBlockTest(); // 这种情况输出的是2 3 1 4
static {
System.out.println("1 b=" + b); // b=112
}
{
System.out.println("2 a=" + a + " b=" + b); // a=110 b=112
}
CodeBlockTest() {
System.out.println("3 a=" + a + " b=" + b); // a=110 b=112
}
public static void main(String[] args) { // 1 2 3 2 3 4
new CodeBlockTest();
new CodeBlockTest();
System.out.println("4");
}
}
package com.whatsmars.base;
import java.io.InputStream;
import java.util.Properties;
/**
* Created by shenhongxi on 15/7/24.
*/
public class PropertiesUtils {
private static Properties properties = new Properties();
static {
try {
InputStream in = PropertiesUtils.class.getClassLoader().getResourceAsStream("conf.properties");
properties.load(in);
} catch (Exception e) {}
}
public static void main(String[] args) {
System.out.print(properties.getProperty("max"));
}
}
package com.itlong.whatsmars.base.collection;
package com.whatsmars.base.collection;
import java.util.Collections;
import java.util.HashMap;
......
package com.whatsmars.base.dp.factory;
public class CarFactory extends VehicleFactory {
@Override
Moveable create() {
return new Car();
}
}
package com.whatsmars.base.dp.factory;
public class Plane implements Moveable {
@Override
public void run() {
System.out.println("plane run...");
}
}
package com.itlong.whatsmars.base.dp.factory.abstractfac;
package com.whatsmars.base.dp.factory.abstractfac;
public class AK47 extends Weapon {
public void shoot() {
......
package com.whatsmars.base.dp.factory.abstractfac;
public abstract class AbstractFactory {
abstract Vehicle createVehicle();
abstract Weapon createWeapon();
abstract Food createFood();
}
package com.whatsmars.base.dp.factory.abstractfac;
public class Apple extends Food {
public void printName() {
System.out.println("Apple...");
}
}
package com.itlong.whatsmars.base.dp.factory.abstractfac;
package com.whatsmars.base.dp.factory.abstractfac;
public class Broom extends Vehicle {
......
package com.whatsmars.base.dp.factory.abstractfac;
public class Car extends Vehicle {
public Car() {}
public void run() {
System.out.println("car running...");
}
}
package com.whatsmars.base.dp.factory.abstractfac;
public abstract class Food {
abstract void printName();
}
package com.itlong.whatsmars.base.dp.factory.abstractfac;
package com.whatsmars.base.dp.factory.abstractfac;
public class MagicFactory extends AbstractFactory {
......
package com.whatsmars.base.dp.factory.abstractfac;
public class MagicStick extends Weapon {
@Override
void shoot() {
System.out.println("MagicStick shooting...");
}
}
package com.itlong.whatsmars.base.dp.factory.abstractfac;
package com.whatsmars.base.dp.factory.abstractfac;
public class Mushroom extends Food {
......
package com.itlong.whatsmars.base.dp.factory.abstractfac;
package com.whatsmars.base.dp.factory.abstractfac;
public class Test {
public static void main(String[] args) {
......
package com.itlong.whatsmars.base.dp.factory.abstractfac;
package com.whatsmars.base.dp.factory.abstractfac;
public abstract class Vehicle {
abstract void run();
......
package com.whatsmars.base.dp.filter;
public class FaceFilter implements Filter {
@Override
public String doFilter(String str) {
return str.replace(":)", "^V^");
}
}
package com.whatsmars.base.dp.filter;
public interface Filter {
String doFilter(String str);
}
package com.whatsmars.base.dp.filter;
import java.util.ArrayList;
import java.util.List;
public class FilterChain implements Filter {
List<Filter> filters = new ArrayList<Filter>();
public FilterChain addFilter(Filter f) {
this.filters.add(f);
return this;
}
public String doFilter(String str) {
String r = str;
for(Filter f: filters) {
r = f.doFilter(r);
}
return r;
}
}
package com.whatsmars.base.dp.filter;
public class HTMLFilter implements Filter {
@Override
public String doFilter(String str) {
//process the html tag <>
String r = str.replace('<', '[')
.replace('>', ']');
return r;
}
}
package com.itlong.whatsmars.base.dp.filter;
package com.whatsmars.base.dp.filter;
import java.nio.charset.Charset;
import java.util.zip.Adler32;
......
package com.itlong.whatsmars.base.dp.filter.web;
package com.whatsmars.base.dp.filter.web;
import java.util.ArrayList;
import java.util.List;
......
package com.itlong.whatsmars.base.dp.filter.web;
package com.whatsmars.base.dp.filter.web;
public class HTMLFilter implements Filter {
......
package com.whatsmars.base.dp.filter.web;
public class Request {
String requestStr;
public String getRequestStr() {
return requestStr;
}
public void setRequestStr(String requestStr) {
this.requestStr = requestStr;
}
}
package com.whatsmars.base.dp.filter.web;
public class Response {
String responseStr;
public String getResponseStr() {
return responseStr;
}
public void setResponseStr(String responseStr) {
this.responseStr = responseStr;
}
}
package com.itlong.whatsmars.base.dp.iterator;
package com.whatsmars.base.dp.iterator;
public class Cat {
public Cat(int id) {
......
package com.itlong.whatsmars.base.dp.iterator;
package com.whatsmars.base.dp.iterator;
public class GenericArrayList<E> {
Object[] objects = new Object[10];
......
package com.itlong.whatsmars.base.dp.iterator;
package com.whatsmars.base.dp.iterator;
public interface Iterator {
Object next();
......
package com.itlong.whatsmars.base.dp.iterator;
package com.whatsmars.base.dp.iterator;
public class LinkedList implements Collection {
......
package com.itlong.whatsmars.base.dp.observer;
package com.whatsmars.base.dp.observer;
import java.util.Observable;
import java.util.Observer;
......
package com.whatsmars.base.dp.observer;
import java.util.List;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
Button b = new Button();
b.addActionListener(new MyActionListener());
b.addActionListener(new MyActionListener2());
b.buttonPressed();
}
}
class Button {
private List<ActionListener> listeners = new ArrayList<ActionListener>();
public void buttonPressed() {
ActionEvent ae = new ActionEvent(System.currentTimeMillis(), this);
for(int i = 0; i < listeners.size(); i++) {
ActionListener l = listeners.get(i);
l.actionPerformed(ae);
}
}
public void addActionListener(ActionListener l) {
listeners.add(l);
}
}
class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("button pressed!");
}
}
class MyActionListener2 implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("button pressed2!");
}
}
interface ActionListener {
void actionPerformed(ActionEvent e);
}
class ActionEvent {
long when;
Object source;
public ActionEvent(long when, Object source) {
this.when = when;
this.source = source;
}
}
package com.whatsmars.base.dp.proxy;
public class Client {
public static void main(String[] args) throws Exception {
Tank t = new Tank();
InvocationHandler h = new TimeHandler(t);
Moveable m = (Moveable)Proxy.newProxyInstance(Moveable.class, h);
m.move();
}
}
//可以对任意的对象、任意的接口方法,实现任意的代理
\ No newline at end of file
package com.whatsmars.base.dp.proxy;
import java.lang.reflect.Method;
public interface InvocationHandler {
public void invoke(Object o, Method m);
}
package com.itlong.whatsmars.base.dp.proxy;
package com.whatsmars.base.dp.proxy;
import java.io.File;
import java.io.FileWriter;
......
package com.whatsmars.base.dp.proxy;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;
public class Test1 {
public static void main(String[] args) throws Exception{
String rt = "\r\n";
String src =
"package com.bjsxt.proxy;" + rt +
"public class TankTimeProxy implements Moveable {" + rt +
" public TankTimeProxy(Moveable t) {" + rt +
" super();" + rt +
" this.t = t;" + rt +
" }" + rt +
" Moveable t;" + rt +
" @Override" + rt +
" public void move() {" + rt +
" long start = System.currentTimeMillis();" + rt +
" System.out.println(\"starttime:\" + start);" + rt +
" t.move();" + rt +
" long end = System.currentTimeMillis();" + rt +
" System.out.println(\"time:\" + (end-start));" + rt +
" }" + rt +
"}";
String fileName = System.getProperty("user.dir")
+ "/src/com/bjsxt/proxy/TankTimeProxy.java";
File f = new File(fileName);
FileWriter fw = new FileWriter(f);
fw.write(src);
fw.flush();
fw.close();
//compile
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null, null, null);
Iterable units = fileMgr.getJavaFileObjects(fileName);
CompilationTask t = compiler.getTask(null, fileMgr, null, null, null, units);
t.call();
fileMgr.close();
//load into memory and create an instance
URL[] urls = new URL[] {new URL("file:/" + System.getProperty("user.dir") +"/src")};
URLClassLoader ul = new URLClassLoader(urls);
Class c = ul.loadClass("com.bjsxt.proxy.TankTimeProxy");
System.out.println(c);
Constructor ctr = c.getConstructor(Moveable.class);
Moveable m = (Moveable)ctr.newInstance(new Tank());
m.move();
}
}
package com.whatsmars.base.dp.proxy.test;
import com.whatsmars.base.dp.proxy.InvocationHandler;
import com.whatsmars.base.dp.proxy.Proxy;
public class Client {
public static void main(String[] args) throws Exception {
UserMgr mgr = new UserMgrImpl();
InvocationHandler h = new TransactionHandler(mgr);
//TimeHandler h2 = new TimeHandler(h);
UserMgr u = (UserMgr) Proxy.newProxyInstance(UserMgr.class, h);
u.addUser();
}
}
package com.whatsmars.base.dp.proxy.test;
import java.lang.reflect.Method;
import com.whatsmars.base.dp.proxy.InvocationHandler;
public class TransactionHandler implements InvocationHandler {
private Object target;
public TransactionHandler(Object target) {
super();
this.target = target;
}
@Override
public void invoke(Object o, Method m) {
System.out.println("Transaction Start");
try {
m.invoke(target);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Transaction Commit");
}
}
package com.itlong.whatsmars.base.dp.proxy.test;
package com.whatsmars.base.dp.proxy.test;
public interface UserMgr {
void addUser();
......
package com.whatsmars.base.dp.proxy.test;
public class UserMgrImpl implements UserMgr {
@Override
public void addUser() {
System.out.println("1: 插入记录到 user 表");
System.out.println("2: 做日志记录到另一张表");
}
}
package com.itlong.whatsmars.base.nio;// $Id$
package com.whatsmars.base.nio;// $Id$
import java.io.*;
import java.nio.*;
......
package com.itlong.whatsmars.base.nio;// $Id$
package com.whatsmars.base.nio;// $Id$
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class CreateArrayBuffer
public class CreateBuffer
{
static public void main( String args[] ) throws Exception {
byte[] array = new byte[1024];
ByteBuffer buffer = ByteBuffer.wrap( array );
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
buffer.put( (byte)'a' );
buffer.put( (byte)'b' );
......
package com.whatsmars.base.nio;// $Id$
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
public class MultiPortEcho
{
private int ports[];
private ByteBuffer echoBuffer = ByteBuffer.allocate( 1024 );
public MultiPortEcho( int ports[] ) throws IOException {
this.ports = ports;
go();
}
private void go() throws IOException {
// Create a new selector
Selector selector = Selector.open();
// Open a listener on each port, and register each one
// with the selector
for (int i=0; i<ports.length; ++i) {
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking( false );
ServerSocket ss = ssc.socket();
InetSocketAddress address = new InetSocketAddress( ports[i] );
ss.bind( address );
SelectionKey key = ssc.register( selector, SelectionKey.OP_ACCEPT );
System.out.println( "Going to listen on "+ports[i] );
}
while (true) {
int num = selector.select();
Set selectedKeys = selector.selectedKeys();
Iterator it = selectedKeys.iterator();
while (it.hasNext()) {
SelectionKey key = (SelectionKey)it.next();
if ((key.readyOps() & SelectionKey.OP_ACCEPT)
== SelectionKey.OP_ACCEPT) {
// Accept the new connection
ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking( false );
// Add the new connection to the selector
SelectionKey newKey = sc.register( selector, SelectionKey.OP_READ );
it.remove();
System.out.println( "Got connection from "+sc );
} else if ((key.readyOps() & SelectionKey.OP_READ)
== SelectionKey.OP_READ) {
// Read the data
SocketChannel sc = (SocketChannel)key.channel();
// Echo data
int bytesEchoed = 0;
while (true) {
echoBuffer.clear();
int r = sc.read( echoBuffer );
if (r<=0) {
break;
}
echoBuffer.flip();
sc.write( echoBuffer );
bytesEchoed += r;
}
System.out.println( "Echoed "+bytesEchoed+" from "+sc );
it.remove();
}
}
//System.out.println( "going to clear" );
// selectedKeys.clear();
//System.out.println( "cleared" );
}
}
static public void main( String args[] ) throws Exception {
if (args.length<=0) {
System.err.println( "Usage: java MultiPortEcho port [port port ...]" );
System.exit( 1 );
}
int ports[] = new int[args.length];
for (int i=0; i<args.length; ++i) {
ports[i] = Integer.parseInt( args[i] );
}
new MultiPortEcho( ports );
}
}
package com.itlong.whatsmars.base.nio;// $Id$
package com.whatsmars.base.nio;// $Id$
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class WriteSomeBytes
public class ReadAndShow
{
static private final byte message[] = { 83, 111, 109, 101, 32,
98, 121, 116, 101, 115, 46 };
static public void main( String args[] ) throws Exception {
FileOutputStream fout = new FileOutputStream( "/Users/javahongxi/writesomebytes.txt" );
FileChannel fc = fout.getChannel();
FileInputStream fin = new FileInputStream( "readandshow.txt" );
FileChannel fc = fin.getChannel();
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
for (int i=0; i<message.length; ++i) {
buffer.put( message[i] );
}
fc.read( buffer );
buffer.flip();
fc.write( buffer );
int i=0;
while (buffer.remaining()>0) {
byte b = buffer.get();
System.out.println( "Character "+i+": "+((char)b) );
i++;
}
fout.close();
fin.close();
}
}
package com.whatsmars.base.nio;// $Id$
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class SliceBuffer
{
static public void main( String args[] ) throws Exception {
ByteBuffer buffer = ByteBuffer.allocate( 10 );
for (int i=0; i<buffer.capacity(); ++i) {
buffer.put( (byte)i );
}
buffer.position( 3 );
buffer.limit( 7 );
ByteBuffer slice = buffer.slice();
for (int i=0; i<slice.capacity(); ++i) {
byte b = slice.get( i );
b *= 11;
slice.put( i, b );
}
buffer.position( 0 );
buffer.limit( buffer.capacity() );
while (buffer.remaining()>0) {
System.out.println( buffer.get() );
}
}
}
package com.whatsmars.base.nio;// $Id$
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class TypesInByteBuffer
{
static public void main( String args[] ) throws Exception {
ByteBuffer buffer = ByteBuffer.allocate( 64 );
buffer.putInt( 30 );
buffer.putLong( 7000000000000L );
buffer.putDouble( Math.PI );
buffer.flip();
System.out.println( buffer.getInt() );
System.out.println( buffer.getLong() );
System.out.println( buffer.getDouble() );
}
}
package com.itlong.whatsmars.base.nio.qing;
package com.whatsmars.base.nio.qing;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
......
package com.itlong.whatsmars.base.nio.qing;
package com.whatsmars.base.nio.qing;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
......
package com.itlong.whatsmars.base.nio.qing;
package com.whatsmars.base.nio.qing;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
......
package com.itlong.whatsmars.base.rmi;
package com.whatsmars.base.rmi;
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
......
package com.whatsmars.base.rmi;
import java.io.Serializable;
/**
* Created by shenhongxi on 2016/4/18.
*/
public class User implements Serializable {
private static final long serialVersionUID = 7105466693678286106L;
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.itlong.whatsmars.base.rmi;
package com.whatsmars.base.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
......
package com.whatsmars.base.socket;
import java.io.*;
import java.net.*;
public class TCPServerModel {
boolean started;
ServerSocket ss;
public static void main(String[] args) {
new TCPServerModel().start();
}
private void start() {
try {
ss = new ServerSocket(5555);
started = true;
System.out.println("Server started");
} catch (BindException e) {//���쳣
System.out.println("�˿�ʹ����....\n" + "��ص���س����������з�������");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
try {
while(started) {
Socket s = ss.accept();
Client c = new Client(s);
System.out.println("a client connected!");
new Thread(c).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ss != null) ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class Client extends Thread {
private Socket s;
private DataInputStream dis;
public Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
System.out.println(dis.readUTF());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dis != null) dis.close();
if (s != null) s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.itlong.whatsmars.base.thread;
package com.whatsmars.base.thread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
......
package com.whatsmars.base.thread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueTest {
public static void main(String[] args) {
final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(3);
for (int i = 0; i < 2; i++) {
new Thread() {
public void run() {
while (true) {
try {
Thread.sleep((long) (Math.random() * 1000));
System.out.println(Thread.currentThread().getName()
+ "准备放数据!");
queue.put(1);
System.out.println(Thread.currentThread().getName()
+ "已经放了数据," + "队列目前有" + queue.size()
+ "个数据");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
new Thread() {
public void run() {
while (true) {
try {
// 将此处的睡眠时间分别改为100和1000,观察运行结果
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()
+ "准备取数据!");
queue.take();
System.out.println(Thread.currentThread().getName()
+ "已经取走数据," + "队列目前有" + queue.size() + "个数据");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
package com.itlong.whatsmars.base.thread;
package com.whatsmars.base.thread;
import java.util.Random;
import java.util.concurrent.Callable;
......
package com.itlong.whatsmars.base.thread;
package com.whatsmars.base.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockTest {
public class ConditionCommunication {
/**
* @param args
*/
public static void main(String[] args) {
new LockTest().init();
}
private void init() {
final Outputer outputer = new Outputer();
final Business business = new Business();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("zhangxiaoxiang");
for (int i = 1; i <= 50; i++) {
business.sub(i);
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("lihuoming");
}
}
}).start();
for (int i = 1; i <= 50; i++) {
business.main(i);
}
}
static class Outputer {
static class Business {
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
private boolean bShouldSub = true;
public void output(String name) {
int len = name.length();
public void sub(int i) {
lock.lock();
try {
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
while (!bShouldSub) {
try {
condition.await();
} catch (Exception e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("sub thread sequence of " + j
+ ",loop of " + i);
}
System.out.println();
bShouldSub = false;
condition.signal();
} finally {
lock.unlock();
}
}
public synchronized void output2(String name) {
int len = name.length();
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
public static synchronized void output3(String name) {
int len = name.length();
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
public void main(int i) {
lock.lock();
try {
while (bShouldSub) {
try {
condition.await();
} catch (Exception e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 100; j++) {
System.out.println("main thread sequence of " + j
+ ",loop of " + i);
}
bShouldSub = true;
condition.signal();
} finally {
lock.unlock();
}
System.out.println();
}
}
}
package com.itlong.whatsmars.base.thread;
package com.whatsmars.base.thread;
import java.util.concurrent.atomic.AtomicInteger;
......
package com.itlong.whatsmars.base.thread;
package com.whatsmars.base.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册