ThreadLocal的详解 : https://www.cnblogs.com/dolphin0520/p/3920407.html
新建线程的几种方法
1、继承Thread类
2、实现Runnable接口
3、实现Callable接口,配合FutureTask,最后的返回结果会在FutureTask对象的get方法中
代码中有些怪异的原因 是因为内部类是动态的,也就是开头以public class开头。而主程序是public static class main。在Java中,类中的静态方法不能直接调用动态方法。只有将某个内部类修饰为静态类,然后才能够在静态类中调用该类的成员变量与成员方法。所以解决办法是将public class改为public static class. 或者改成的new test().new thread():
class test
{
public static void main (String[] args){
System.out.println("test -main");
//***************************************
new Thread(new Runnable() {
public void run() {
System.out.println("test -main -thread 111");
}
}).start();
//***************************************
new test().new Thread2().start();
//***************************************
new Thread(new test().new Thread3()).start();
//***************************************
FutureTask<Integer> futureTask = new FutureTask<>(new test().new Thread4());
new Thread(futureTask).start();
try {
System.out.println("test -main -thread 444 result:" + futureTask.get());
} catch (Exception e) {
System.out.println("futureTask.get() erro" );
e.printStackTrace();
}
}
public class Thread2 extends Thread{
public void run() {
System.out.println("test -main -thread 222");
}
}
public class Thread3 implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("test -main -thread 333");
}
}
public class Thread4 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("test -main -Thread 444");
return 100;
}
}
}
打印结果:
test -main
test -main -thread 111
test -main -thread 222
test -main -thread 333
test -main -Thread 444
test -main -thread 444 result:100