有两种方式:从Tread中派生出新的子类、实现Runnable接口、还有一种习惯用法
一、从Tread中派生出新的子类
创建片段
//给线程起名 A,并创建
new 类型("线程名字").start();
完整的创建一个线程,并调用(为了给线程起名字,创建了域name,并类里边创建了构造器)
public class Try extends Thread{
private String name;
public Try(String name) {
this.name=name;
}
public void run() {
synchronized(this) {
for(int i=0;i<4;i++) {
System.out.println(name+" : "+i);
}
}
}
public static void main(String[] args) {
new Try("A").start();
}
}
输出结果:
A : 0
A : 1
A : 2
A : 3
二、实现Runnable接口
创建片段
//给线程起名 A,并创建
new Thread(创建类,"A").start();
完整的创建一个线程,并调用
public class Try implements Runnable{
public void run() {
synchronized(this) {
for(int i=0;i<4;i++) {
System.out.println(Thread.currentThread().getName()+" : "+i);
}
}
}
public static void main(String[] args) {
new Thread(new Try(),"A").start();
}
}
输出结果:
A : 0
A : 1
A : 2
A : 3
三、习惯用法
创建片段
new Thread(new Runnable() {
public void run() {
//TODO
}
}).start();
完整的创建一个线程,并调用
public class Try {
public void method1() {
synchronized(this) {
for(int i=0;i<4;i++) {
System.out.println(Thread.currentThread().getName()+" : "+i);
}
}
}
public static void main(String[] args) {
final Try tt = new Try();
//创建线程并且起名字
Thread A = new Thread(new Runnable() { public void run() { tt.method1(); } }, "A" );
A.start();
}
}
输出结果:
A : 0
A : 1
A : 2
A : 3