多线程
线程简介
用户自己写的线程:用户线程
JVM的线程:守护线程
线程创建(线程开启并不一定立即执行,由cpu调度)
- 继承Thread类
public class ExtendThread extends Thread {
private int i;
public static void main(String[] args) {
for(int j = 0;j < 50;j++) {
//调用Thread类的currentThread()方法获取当前线程
System.out.println(Thread.currentThread().getName() + " " + j);
if(j == 10) {
//创建并启动第一个线程
new ExtendThread().start();
//创建并启动第二个线程
new ExtendThread().start();
}
}
}
public void run() {
for(;i < 100;i++) {
//当通过继承Thread类的方式实现多线程时,可以直接使用this获取当前执行的线程
System.out.println(this.getName() + " " + i);
}
}
}
- 实现Runnable接口
public class ImpRunnable implements Runnable {
private int i;
@Override
public void run() {
for(;i < 50;i++) {
//当线程类实现Runnable接口时,要获取当前线程对象只有通过Thread.currentThread()获取
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
public static void main(String[] args) {
for(int j = 0;j < 30;j++) {
System.out.println(Thread.currentThread().getName() + " " + j);
if(j == 10) {
ImpRunnable thread_target = new ImpRunnable();
//通过new Thread(target,name)的方式创建线程
new Thread(thread_target,"线程1").start();
new Thread(thread_target,"线程2").start();
}
}
}
}
- 实现Callable接口
import java.util.concurrent.*;
public class Thread3 implements Callable<Boolean> {
private int tictets=10;
@Override
public Boolean call() throws Exception{
if(Thread.currentThread().getName()=="小明")
{
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.printf("出现异常");
}
}
while(true)
{
if(tictets<=0) break;
System.out.println(Thread.currentThread().getName()+"拿到了第"+tictets--+"张票");
}
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
Thread3 t1=new Thread3();
Thread3 t2=new Thread3();
ExecutorService ser= Executors.newFixedThreadPool(2);
Future<Boolean> r1= ser.submit(t1);
Future<Boolean> r2= ser.submit(t2);
boolean rs1= r1.get();
boolean rs2=r2.get();
System.out.printf(String.valueOf(rs1));
System.out.printf(String.valueOf(rs2));
ser.shutdown();
}
}