多线程创建方式
1、继承Thread
public class ThreadTest { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); for (int i = 0; i < 1001; i++) { if(i % 2 != 0){ System.out.println(i + "main"); } } } } class MyThread extends Thread{ @Override public void run() { for (int i = 0; i < 1001; i++) { if(i % 2 == 0){ System.out.println(i); } } } }
Thread.currentThread()获取当前线程,setName getName 设置线程名称
if (i ==20){
myThread.join();
}
当前线程进入阻塞,等myThread线程执行完了再执行
2、实现runaable接口
public class ThreadTest1{ public static void main(String[] args) { MyThread1 myThread1 = new MyThread1(); Thread thread = new Thread(myThread1); thread.start(); for (int i = 1001; i < 2000; i++) { System.out.println(Thread.currentThread().getName()+i); } } } class MyThread1 implements Runnable{ @Override public void run() { for (int i = 0; i < 1000; i++) { System.out.println(Thread.currentThread().getName()+i); } } }