JAVA多线程
1.定义一个Thread的子类
2.重写run方法
3.在需要的定法创建子类对象
4.调用子类对象的start方法(不要调用run方法,调用run就变成单线程了)
1 public class Main { 2 public static void main(String[] args) { 3 SubThread st = new SubThread(); 4 st.start(); // 启动子线程,调用相应的run方法 5 6 for (int i = 1; i < 100; i++) { 7 System.out.println(Thread.currentThread().getName() + ":" + i); 8 } 9 } 10 11 12 } 13 14 // 1.继承thread类 15 // 2.重写run 16 class SubThread extends Thread { 17 public void run() { 18 for (int i = 1; i<= 100; i++) { 19 System.out.println(i); 20 } 21 } 22 }
Thread.getCurrentThread().getName() 可以获取线程名字
st1.setName("name"); // 设置子线程名字
Thread.currentThread().setName("name"); // 设置当前线程名字(主线程)
st1.yield(); // 调用次方法的线程自动释放cpu,但是下次也可能被自己抢到
join(); // 在A线程中调用B线程的join方法,当执行到此方法,A方法停止执行,直至B线程执行完,然后执行A线程
isAlive(); // 判断线程是否还存活
sleep(long l); //显示的让当前线程睡眠l 毫秒
wait();
notify();
notifyAll();