java经典代码段 一段java代码的详细解说

java线程的经典代码package threadgroup;
class ThreadDemo3 extends Thread {
private String name;
private int delay;
public ThreadDemo3(String sname, int i_delay) {
name = sname;
delay = i_delay;
}
public void run() {
try {
sleep(delay);
} catch (InterruptedException e) {
}
System.out.println("多线程测试!\n" + name + "\n" + delay);
}
}
public class testMyThread {
public static void main(String[] args) {
ThreadDemo3 th1,th2,th3;
th1 = new ThreadDemo3("线程1", (int) (Math.random() * 900));
th2 = new ThreadDemo3("线程2", (int) (Math.random() * 900));
th3 = new ThreadDemo3("线程3", (int) (Math.random() * 900));
th1.start();
th2.start();
th3.start();
}
}
package threadgroup;
public class threadDemo {
public static void main(String[] args) {
Thread t = Thread.currentThread();
t.setName("你好吗?");
System.out.println("正在进行的Thread是:" + t);
try {
for (int i = 0; i5; i++) {
System.out.println("我不叫穆继超" + i);
Thread.sleep(3000);
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("Thread has wrong" + e.getMessage());
【java经典代码段 一段java代码的详细解说】}
}
}
package threadgroup;
public class threadDemo2 implements Runnable {
public threadDemo2() {
Thread t1 = Thread.currentThread();
t1.setName("第一个主进程");
System.out.println("正在运行" + t1);
Thread t2 = new Thread(this, "");
System.out.println("在创建一个进程");
t2.start();
try {
System.out.println("使他进入第一个睡眠状态");
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Thread has wrong" + e.getMessage());
}
System.out.println("退出第一个进程");
}
public void run() {
try {
for (int i = 0; i5; i++) {
System.out.println("进程" + i);
Thread.sleep(3000);
}
} catch (InterruptedException e) {
// TODO: handle exception
System.out.println("Thread has wrong" + e.getMessage());
}
System.out.println("退出第二个进程");
}
public static void main(String[] args) {
new threadDemo2();
}
}
求一段简单的java代码不知道是否理解对了你的意思,大概写了一下:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
public class FileReadAndWrite {
private static final int DEFAULT_BUFFER_SIZE = 1024;
public static void main(String[] args) {
File file = new File("E:/workspace/FileIOTest/src/a.txt");
String str = file2String(file, "UTF-8");
str = str.replace('d', 'f');
string2File(str,"E:/workspace/FileIOTest/src/b.txt");
System.out.println("处理完毕");
}
/**
* 文本文件转换为指定编码的字符串
*
* @param file
*文本文件
* @param encoding
*编码类型
* @return 转换后的字符串
* @throws IOException
*/
public static String file2String(File file, String encoding) {
InputStreamReader reader = null;
StringWriter writer = new StringWriter();
try {
if (encoding == null || "".equals(encoding.trim())) {
reader = new InputStreamReader(new FileInputStream(file),
encoding);
} else {
reader = new InputStreamReader(new FileInputStream(file));
}
// 将输入流写入输出流

推荐阅读