分别用继承Thread和实现Runnable两种方式定义线程,两种内部类,调用时外部类的对象访问。
以下demo测试了三个线程,打印内容用文件作为控制台展示。
定义线程的两种方式
- 继承thread类
- 继承thread类
- 重写run方法
- 调用start方法启动线程
- 实现runnable接口
- 定义类实现runnable接口
- new Thread(runnable实现类)
- 调用start方法启动线程
线程的关闭: 通过标记flag关闭线程
/**
* @author cuijiao
*
*/
public class MutiThread {
/**
* @param args
*/
public static void main(String[] args) {
// 1.Thread
MutiThread mt = new MutiThread();
Thread myThread = mt.new MyTread("thread1");// 只能通过外部类的对象访问非静态内部类
myThread.start();
// 2.Runnable
Runnable myRun = mt.new MyRunnable();
Thread thread = new Thread(myRun, "run2");
thread.start();
// 3.主线程
int i = 0;
boolean flag = true;
while (flag) {
FileConsole.print(Thread.currentThread().getName() + i);
i++;
if (i >= 50) {// 通过标记flag关闭线程
flag = false;
}
}
}
// 1.继承Thread
private class MyTread extends Thread {
public MyTread(String name) {
super(name);
}
@Override
public void run() {
int i = 0;
while (true) {
FileConsole.print(Thread.currentThread().getName() + i);
i++;
}
}
}
// 2.实现Runnable接口
private class MyRunnable implements Runnable {
@Override
public void run() {
int i = 0;
while (true) {
FileConsole.print(Thread.currentThread().getName() + i);
i++;
}
}
}
}
其中打印代码为:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* @author cuijiao
*
*/
public class FileConsole {
/**
* 用文件充当控制台(可查看行数无限制)
*
* @param str
*/
public static void print(String str) {
File file = new File("E:\\console.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(file, true);// 可追加内容
bw = new BufferedWriter(fw);
bw.write(str);
bw.newLine();// 换行
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
bw = null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
进程:系统资源分配的最小单位
线程:系统运行的最小单位,一个进程至少包含一个线程。
java程序:至少包含两个线程:主线程,GC