线程
/**
*实现线程的第一种方法
*继承线程
*重写run方法
*/
public class ThreadDemo extends Thread{
//重写run方法
@Override
public void run() {
for(int i = 0;i < 5;i++){
try {
//休眠2秒
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
}
public static void main(String[] args) {
//运行线程只需要两步
//1:new一个线程
ThreadDemo t = new ThreadDemo();
//2:运行线程
t.start();
}
}
实现接口Runnable
/**
* 实现接口Runnable
* implements Runnable
*/
public class ThreadDemo4 implements Runnable{
//重写run方法
@Override
public void run() {
for(int i = 0;i < 5;i++){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
}
public static void main(String[] args) {
ThreadDemo4 demo4 = new ThreadDemo4();
new Thread(demo4).start();
}
}
匿名内部类创建多线程
public class ThreadDemo3 {
public static void anonymity(){
//匿名内部类
Thread t = new Thread(new Runnable(){
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+","+i);
// System.out.println(i);
}
}
});
t.start();
}
外部类创建多线程
//外部类
static class InnerDemo3 implements Runnable{
@Override
public void run() {
for(int i = 0;i < 5;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
}
}
public static void exterior(){
InnerDemo3 id = new InnerDemo3();
Thread t = new Thread(id);
t.start();
}
匿名内部类和外部类的主方法
public static void main(String[] args) {
anonymity();
exterior();
}
}