1.java实现多线程的方式。
- 继承Thread抽象类重写run方法
public class Demo01 {
public static void main(String[] args) {
System.out.println("begin!");
PrintFlag print = new PrintFlag();
print.start();
System.out.println("end!");
}
}
class PrintFlag extends Thread{
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.print("#");
if(i % 10 == 0) {
System.out.println();
}
}
}
}
- 实现Runnable接口重写run方法
public class Demo02 {
public static void main(String[] args) {
System.out.println("主线程开始执行下载任务。");
// 创建第一个线程并使线程进入就绪状态
new Thread(new DewnloadThread("桃花侠大战菊花怪")).start();
// 创建第二个线程并使线程进入就绪状态
new Thread(new DewnloadThread("变形金刚")).start();
// 创建第三个线程并使线程进入就绪状态
new Thread(new DewnloadThread("三国")).start();
}
}
class DewnloadThread implements Runnable{
private String movie;
public DewnloadThread(String movie) {
this.movie = movie;
}
@Override
public void run() {
for (int i = 1; i <= 1024; i++) {
System.out.println("正在下载" + movie + "的第" + i +"部分");
}
}
}
2.线程的状态。
线程大致分为5中状态:新生状态,就绪状态,运行状态,死亡状态,阻塞状态。
线程状态
3.Thread类中的相关方法。
静态方法:
- public static native Thread currentThread();
获取当前线程对象。 - public static native void yield();
将当前正在执行的线程暂停,将这个线程转为就绪状态。(调用yield方法后当前线程仍然可能被立即执行)。 - public static native void sleep(long millis) throws InterruptedException;
使当前线程阻塞millis毫秒。
实例方法
- public synchronized void start();
使当前线程对象进入就绪状态。 - public final void join() throws InterruptedException
阻塞指定线程待另一个线程执行完成之后再执行。 - public final void setPriority(int newPriority);
设置当前线程的优先级(优先级范围为1~10;数字越大优先级越大) - public final int getPriority();
获取当前线程的优先级 - public final native boolean isAlive();
判断当前线程是否死亡。 - public final String getName();
获取当前线程的名字 - public final synchronized void setName(String name);
设置当前线程的名字