多线程
创建方式
继承,接口,匿名内部类
//继承类
public class Demo extends Thread {
public void run() {
for(int i=1;i<100;i++) {
System.out.println("子线程"+i);
}
}
}
public class test {
public static void main(String[] args) {
Demo a=new Demo();
a.start();
for(int i=1;i<100;i++) {
System.out.println(" "+"主线程"+i);
}
}
}
//接口类
public class Demo {
public static void main(String[] args) {
MyRunnable a=new MyRunnable();
Thread b=new Thread(a,"shi");//为子线程起名字
b.start();
Thread.currentThread().setName("sjf");//为主线程起名字
for(int i=1;i<100;i++) {
System.out.println("ID为:"+Thread.currentThread().getId()+"名字为"+Thread.currentThread().getName());
}
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<100;i++) {
System.out.println("ID为"+Thread.currentThread().getId()+"名字为"+Thread.currentThread().getName());
}
}
}
```java
//内部类
public class Demo1023 {
public static void main(String[] args) throws InterruptedException {
Thread t=new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<100;i++) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+i);
}
}
},"张三");
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<100;i++) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+i);
}
}
},"李四");
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for(char a='a';a<='z';a++) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(a);
}
}},"王五");
Thread t3=new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<100;i++) {
System.out.println(Thread.currentThread().getName()+i);
}
}
},"张三");
t3.start();
t1.start();
t2.start();
}
}
这三种都是特别基本的线程创建方式