多线程的创建
public class MyThread extends Thread {
//1.让子类继承Thread线程类
//2.必须重写Thread类的run方法
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("线程输出:" +i);
}
}
}
public class ThreadTest1 {
public static void main(String[] args) {
//3.创建MyThread线程类的对象代表一个线程
Thread t = new MyThread();
//4.启动线程
t.start();
}
}
/*
1.让这个类实现Callable接口
*/
public class MyCallable implements Callable<String> {
private int n;
public MyCallable(int n) {
this.n = n;
}
//2.重写call方法
@Override
public String call() throws Exception {
int sum = 0;
for (int i = 1; i < n; i++) {
sum+=i;
}
return "1-" + n +"的和是:" +sum;
}
}
public class ThreadTest3 {
public static void main(String[] args) throws Exception {
//3.创建一个Callable对象
Callable<String> call = new MyCallable(10);
//4.封装成FutureTask对象
FutureTask<String> f1 = new FutureTask<>(call);
//5.把任务对象交给Thread对象
new Thread(f1).start();
String s = f1.get();
System.out.println(s);
}
}
Thread的常用方法
线程安全
线程同步
线程同步:解决线程安全问题的方案
Tips:对于 synchronized 作用于同步代码,锁为任何我们创建的对象,只要是个对象即可,如 new Object () 可以作为锁,new String () 也可作为锁,当然如果传入 this,那么此时代表当前对象,建议使用this,静态方法中的锁建议使用类名.class作为锁。
/**
* synchronized 修饰实例方法
*/
static final Object objectLock = new Object(); //创建一个对象锁
public static void increase() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + "获取到锁,其他线程在我执行完毕之前,不可进入。" );
synchronized (objectLock) {
sleep(1000);
count++;
System.out.println(Thread.currentThread().getName() + ": " + count);
}
}
同步方法
public synchronized void increaseCount() {
String thread = Thread.currentThread().getName();
System.out.println("当前" + thread + "线程正在操作");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count += 1;
System.out.println("当前" + thread + ":" + count);
}
Lock锁
Api中明确,使用Lock锁必须注意确保在锁定时执行的所有代码由try-finally或try-catch保护,以确保在必要时释放锁定