1 java程序天生就是多线程,证明方法如下
public class OnlyMain {
public static void main(String[] args) {
ThreadMXBean threadMXBean= ManagementFactory.getThreadMXBean();
ThreadInfo[] threadInfos=threadMXBean.dumpAllThreads(false,false);
for(ThreadInfo threadInfo:threadInfos){
System.out.println("["+threadInfo.getThreadId()+"]"+" "
+threadInfo.getThreadName());
}
}
}
2启动新线程的方法
- Thread类
- Runnable接口
- Callable接口
分析:因为java类是单继承、多实现,所以会出现Runnable接口,又因为Runnable接口返回值是void类型,所以出现了有返回值的Callable接口。
测试代码如下
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class NewThread {
public static class UseThread extends Thread {
@Override
public void run() {
System.out.println("I am extends Thread");
}
}
public static class UseRun implements Runnable {
@Override
public void run() {
System.out.println("I am implements Runnable");
}
}
public static class UseCall implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("I am implements Callable");
return "callResult";
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
UseThread useThread = new UseThread();
useThread.start();
UseRun useRun = new UseRun();
Thread t = new Thread(useRun);
t.start();
UseCall useCall = new UseCall();
FutureTask futureTask = new FutureTask(useCall);
Thread tc = new Thread(futureTask);
tc.start();
System.out.println(futureTask.get());
}
}
3停止线程的方法
- 自然停止;
- 抛出异常导致停止;
- stop(),什么也不管,暴力停止,会造成某种错误,已经被废弃;
- suspend(),挂起线程,并不会放弃资源,这样子会造成死锁,已经被废弃;
- interrupt(),目前使用该方法来停止线程,这个方法只是打个招呼,还是相对安全的,具体停止不停止、什么时候停止由当前线程决定。
其他属性 :
isInterrupted()用来判断线程是不是停止,返回true或false;
interrupted()用来把中断标志位的值置位false