java中对线程理解以及创建方式
1,进程和线程的对比进程:是一个程序的集合 线程:一个进程中包含多个线程2,线程的几种状态
NEW:新建 RUNNABLE:运行中 BLOCKED:线程阻塞 WAITING:线程等待 TIMED_WAITING:线程超时等待 TERMINATED:线程终止3,创建线程的三种方式
方式一:继承Thread类
public class ThreadDemo extends Thread{
public ThreadDemo(){}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("thread-name:" + Thread.currentThread().getName());
}
}
public static void main(String[] args) {
ThreadDemo thread01 = new ThreadDemo();
ThreadDemo thread02 = new ThreadDemo();
ThreadDemo thread03 = new ThreadDemo();
thread01.start();
thread02.start();
thread03.start();
}
}
方式二:实现Runnable接口
public class ThreadRunnableDemo implements Runnable{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("thread-name:" + Thread.currentThread().getName());
}
}
}
class TestRunnable{
public static void main(String[] args) {
ThreadRunnableDemo threadRunnable = new ThreadRunnableDemo();
Thread thread01 = new Thread(threadRunnable, "线程1");
Thread thread02 = new Thread(threadRunnable, "线程2");
Thread thread03 = new Thread(threadRunnable, "线程3");
thread01.start();
thread02.start();
thread03.start();
}
}
方式三:实现Callable接口
public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable = new MyCallable();
FutureTask futureTask = new FutureTask<>(myCallable);
new Thread(futureTask).start();
Thread thread1 = new Thread(futureTask,"thread-01");
Thread thread2 = new Thread(futureTask,"thread-02");
Thread thread3 = new Thread(futureTask,"thread-03");
thread1.start();
thread2.start();
thread3.start();
}
}
class MyCallable implements Callable{
@Override
public Integer call() throws Exception {
for (int i = 0; i < 5; i++) {
System.out.println("thread-name:" + Thread.currentThread().getName());
}
return 1024;
}
}



