java多线程编程
java实现多线程有两种方法:①:implements Runnable 并重写run(); ②:extends Thread类
Thread类中的一些常用方法:
得到当前运行线程 :Thread.currentThread().getName()
线程休眠 100毫秒: sleep(100)
线程强制运行:jion()
package com.thread;
public class ThreadDemo implements Runnable {
public void fun(){
//Thread.currentThread().getName()得到线程的名字
System.out.println(Thread.currentThread().getName()+" 在运行...");
}
public void run(){
this.fun();
for (int i = 0; i < 10; i++) {
this.fun();
}
}
/**
* isAlive() 线程是否还存活
* sleep(10) 线程休眠,传入毫秒数
* jion() 一个线程必须运行完成之后其他的线程才可以继续运行,表示强制性运行;
*
*
* 重点:
* 得到当前运行线程 :Thread.currentThread().getName()
* 线程休眠 100毫秒: sleep(100)
* 线程强制运行:jion()
*/
public static void main(String[] args)throws Exception {
ThreadDemo demo = new ThreadDemo();
Thread t1 = new Thread(demo,"线程1");
// Thread t2 = new Thread(demo,"线程2");
// Thread t3 = new Thread(demo,"线程3");
// t1.setName("线程1");
t1.start();
t1.sleep(10);
System.out.println("线程是否存活:"+t1.isAlive());
// t2.setName("线程2");
// t2.start();
// t3.setName("线程3");
// t3.start();
// for (int i = 0; i < 10; i++) {
// demo.fun();//打印的是main,主线程
// }
}
}

浙公网安备 33010602011771号