文章目录
线程创建
1. 继承Thread类
重写run方法
public class ThreadDemo extends Thread{
@Override
public void run() {
System.out.println("线程启动");
}
}
class testDemo{
public static void main(String[] args) {
ThreadDemo t = new ThreadDemo();
t.start();
}
}
2. 实现runable接口
重写run方法
public class RunnableDemo implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName()+"执行"+i);
}
}
}
class testRunnable{
public static void main(String[] args) {
RunnableDemo RunT = new RunnableDemo();
Thread t = new Thread(RunT);
t.start();
}
}
3. 实现 Callable
重写call方法
public class CallableDemo implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return 10+10;
}
}
class testCallable{
public static void main(String[] args) throws ExecutionException, InterruptedException {
CallableDemo call = new CallableDemo();
FutureTask<Integer> ft = new FutureTask<>(call);
Thread t = new Thread(ft);
t.start();
// 获取返回结果
Integer num = ft.get();
System.out.println(num);
}
}
线程方法
String getName() //获取线程的名称
void setName(String name) //设置线程的名字(构造方法也可以设置名字),没有给线程设置名字线程默认名字
static Thread currentThread() //获取当前线程的对象
static void sleep(long time) //让线程休眠指定时间,单位是毫秒
setPriority(int newPriority) //设置线程优先级
final int getPriority() //获取线程的优先级
// 当非守护线程结束后,守护线程也会陆续结束
final void setDaemon(boolean on) //设置为守护线程
public final boolean isDaemon() // 判断是否为守护线程
// 出让当前线程的执行权,从新抢夺cpu执行权利
public static void yield()
// 将线程插入到当前线程之前,执行完线程后再执行当前线程
public static void join()
public final native boolean isAlive() //判断线程是否存活
//中断线程(抛出异常)-如果线程没有处于可中断状态(sleep,wait等),
//调用方法只是简单地设置了线程的中断标志位,并不会中断线程的执行。
public void interrupt()
public boolean isInterrupted() //判断线程是否被中断
public State getState() //返回线程状态
public class ThreadDemo extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
// 睡眠10毫秒
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 获取当前线程对象,并获取名称
System.out.println(Thread.currentThread().getName()+"执行");
Thread.yield();// 出让当前线程的执行权
}
}
}
class testDemo{
public static void main(String[] args) throws InterruptedException {
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
//设置线程名称
t1.setName("线程1");
t2.setName("线程2");
// 设置t2的线程优先级为6
t2.setPriority(6);
// 获取线程优先级(1-10)默认为5
System.out.println("t1线程优先级"+t1.getPriority());
System.out.println("t2线程优先级"+t2.getPriority());
RunnableDemo run = new RunnableDemo();
Thread t3 = new Thread(run,"线程3");
// 将t3线程设置为守护线程,线程3不会执行100次,会随着其他线程结束就会结束
t3.setDaemon(true);
// 启动线程
t1.start();
t2.start();
t3.start();
}
t1.join();
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"执行");
}
锁
1. synchronized
(1) synchronized (同步)代码块
public void run() {
while (true) {
// 代码块编写,MyThread.class为锁对象
synchronized (MyThread.class) {
if (i > 100) break
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName() + " " + i++);
Thread.yield();
}
}
}
(2) synchronized (同步)方法
public void run() {
while (true) {
print100();
}
}
private synchronized static void print100() {
if (i > 100) return;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName() + " " + i++);
Thread.yield();
}
2. Lock
// 获取锁对象,Lock本身为接口
Lock lock = new ReentrantLock();
void lock() // 加锁
void unlock() // 释放锁
static int i = 0;
static Lock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
// 代码块编写,MyThread.class为锁对象
lock.lock();
if (i >= 100) break;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
i++;
System.out.println(Thread.currentThread().getName() + " " + i);
lock.unlock(); // 跳出循环后无法释放锁
}
lock.unlock(); // 释放跳出循环的锁
}
等待唤醒机制
让线程轮流执行
1. synchronized实现
void wait() // 线程等待
void notyfy() // 唤醒单个线程
void notifyAll() // 唤醒所有等待线程
public class MyThread1 extends Thread {
@Override
public void run() {
while (true) {
synchronized (onLook.obj) {
if (onLook.num > onLook.maxNum) return;
else if (onLook.num % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ": " + onLook.num++);
onLook.obj.notifyAll();
} else {
try {
onLook.obj.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
public class MyThread2 extends Thread{
@Override
public void run() {
while (true){
synchronized (onLook.obj){
if (onLook.num>onLook.maxNum)return;
else if (onLook.num%2==0){
try {
onLook.obj.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}else {
System.out.println(Thread.currentThread().getName()+": "+onLook.num++);
onLook.obj.notifyAll();
}
}
}
}
}
public class onLook {
static int num=0;
static int maxNum=10;
static Object obj = new Object();
public static void main(String[] args) {
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
t1.setName("线程1");
t2.setName("线程2");
t1.start();
t2.start();
}
}
2. lock实现:
wait() // 线程等待
signal() // 唤醒单个线程
signalAll() // 唤醒所有等待线程
public class testThread1 extends Thread{
@Override
public void run() {
while (onlooker.i<=10){
onlooker.lock.lock();
try {
if (onlooker.i>10) break;
else if ((onlooker.i % 2)==0) {
onlooker.condition.await();
} else {
System.out.println(Thread.currentThread().getName()+" "+onlooker.i++);
onlooker.condition.signalAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
onlooker.lock.unlock();
}
}
}
}
public class testThread2 extends Thread{
public void run() {
while (onlooker.i<=10){
onlooker.lock.lock();
try {
if (onlooker.i>10) break;
else if (onlooker.i% 2==0){
System.out.println(Thread.currentThread().getName()+" "+onlooker.i++);
onlooker.condition.signalAll();
}else {
onlooker.condition.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
onlooker.lock.unlock();
}
}
}
}
public class onlooker {
public static Lock lock = new ReentrantLock();
public static int i;
/*
Condition是Java中提供的线程同步机制之一,用于实现线程间的等待/通知机制。
它可以让线程在某个条件成立时等待,直到其他线程满足条件并通知它继续执行。
*/
public static Condition condition = lock.newCondition();
public static void main(String[] args) throws InterruptedException {
testThread1 t1 = new testThread1();
testThread2 t2 = new testThread2();
t1.setName("t1线程");
t2.setName("t2线程");
t1.start();
t2.start();
}
}