Thread:
Thread thread = new Thread() {
@Override
public void run() {
System.out.println(“Thread started!”);
}
};
thread.start();
复制代码
Thread类的几个常用的方法:
-
sleep():静态方法,使当前线程睡眠一段时间;
-
currentThread():静态方法,返回对当前正在执行的线程对象的引用;
-
start():开始执行线程的方法,java虚拟机会调用线程内的run()方法;
-
join():使当前线程等待另一个线程执行完毕之后再继续执行,内部调用的是Object类的wait方法实现的;
-
yield():yield意为放弃,yield()方法指当前线程愿意让出对当前处理器的占用。需要注意,即时当前线程调用了yield()方法让出处理机,调度时也有可能继续让该线程竞争获得处理机并运行;
Runnable:
Runnable
是一个函数式接口:
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
复制代码
Runnable不利于线程重用管理
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(“Thread with Runnable started!”);
}
};
Thread thread = new Thread(runnable);
thread.start();
复制代码
ThreadFactory:
ThreadFactory factory = new ThreadFactory() {
int count = 0;
@Override
public Thread newThread(Runnable r) {
count ++;
return new Thread(r, “Thread-” + count);
}
};
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + “started!”);
}
};
Thread thread = factory.newThread(runnable);
thread.start();
Thread thread1 = factory.newThread(runnable);
thread1.start();
复制代码
Executor线程池:
Executor线程池(最为推荐):</