Java线程-基础

进程 VS 线程
并发 VS 并行

线程4种实现方法:
1.Thread
2.Runnable
3.FutureTask+Callable
4.使用线程池

启动线程用cat.start() 为什么不是 cat.run()
原因:
cat.run是一个普通的方法,没有真正启动一个线程,就会把run方法执行完毕,才向下执行
真正实现多线程的是private native void start0();

源码分析:
start() -> start0(),线程并不一定立马执行,只是将线程变为可运行状态
private native void start0();//本地方法,JVM调用,底层是c/c++实现

用户线程 VS 守护线程
守护线程当用户线程都运行结束后自动结束,如垃圾回收
只要其它非守
护线程运行结束了,即使守护线程的代码没有执行完,也会强制结束
thread.setDaemon(true);//设置为守护线程

线程API层面的7种状态:NEW RUNNABLE BLOCKED WAITING TIMED_WAITING TERMINATED
NEW 线程刚被创建,但是还没有调用 start() 方法
RUNNABLE 当调用了 start() 方法之后,Java API 层面的 RUNNABLE 状态涵盖了 操作系统 层面的
【可运行状态】、【运行状态】和【阻塞状态】
BLOCKED , WAITING , TIMED_WAITING 都是 Java API 层面对【阻塞状态】的细分
TERMINATED 当线程代码运行结束
//线程的状态
public class TestState {
    public static void main(String[] args) throws IOException {
        Thread t1 = new Thread("t1") {
            @Override
            public void run() {
            }
        };

        Thread t2 = new Thread("t2") {
            @Override
            public void run() {
                while (true) { // runnable
                }
            }
        };
        t2.start();

        Thread t3 = new Thread("t3") {
            @Override
            public void run() {
                synchronized (TestState.class) {
                    try {
                        Thread.sleep(1000000); // timed_waiting
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        t3.start();

        Thread t4 = new Thread("t4") {
            @Override
            public void run() {
                try {
                    t2.join(); // waiting
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        t4.start();

        Thread t5 = new Thread("t5") {
            @Override
            public void run() {
                synchronized (TestState.class) { // blocked
                    try {
                        Thread.sleep(1000000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        t5.start();

        Thread t6 = new Thread("t6") {
            @Override
            public void run() {
            }
        };
        t6.start();

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("t1 state:" + t1.getState());
        System.out.println("t2 state:" + t2.getState());
        System.out.println("t3 state:" + t3.getState());
        System.out.println("t4 state:" + t4.getState());
        System.out.println("t5 state:" + t5.getState());
        System.out.println("t6 state:" + t6.getState());
    }
}
//线程实现方式
public class Test {

    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.start();//开启子线程

        Dog dog = new Dog();
        Thread thread = new Thread(dog);
        thread.start();//开启子线程

        System.out.println("main主线程启动子线程,main主线程不会阻塞,会继续执行,主线程结束不影响子线程,主线程名:" + Thread.currentThread().getName());
    }
}


//1.extends Thread
class Cat extends Thread {
    @Override
    public void run() {
        while (true) {
            System.out.println("喵喵喵~ " + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


//2.implements Runnable接口
class Dog implements Runnable {
    @Override
    public void run() {
        while (true) {
            System.out.println("汪汪汪~ " + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

总结:
Runnable是一个函数式接口,实现里面的run()抽象方法,表示线程要执行的任务
@FunctionalInterface
public interface Runnable {
	public abstract void run();
}

public class ThreadTest_ {
    public static void main(String[] args) {

		//线程和任务合并在一起
        new Thread("thread1") {
            @Override
            public void run() {
                //要执行的任务
                System.out.println("thread1");
            }
        }.start();

        //线程和任务分开,Runnable配合Thread, Runnable线程要执行的代码
        //创建任务对象
        Runnable task1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("thread2");
            }
        };
        new Thread(task1, "thread2").start();

		//使用lambda简化
        Runnable task2 = () -> System.out.println("thread3");
        new Thread(task2, "thread3").start();

        new Thread(() -> System.out.println("thread4"), "thread4").start();

    }
}

//方式三,FutureTask + Callable
FutureTask接受一个Callable
public FutureTask(Callable<V> callable)

Callable是一个函数式接口,和Runnable类似,多了返回值和抛异常
@FunctionalInterface
public interface Callable<V> {
    V call() throws Exception;
}

FutureTask<Integer> task3 = new FutureTask<>(() -> {
  System.out.println("thread5");
  return 100;
});
new Thread(task3, "thread5").start();
// 主线程阻塞,同步等待 task 执行完毕的结果
System.out.println(task3.get());
//线程的常用方法
public class Test {

    public static void main(String[] args) throws InterruptedException {
        Cat cat = new Cat();
        cat.setName("cat");//设置线程名称
        cat.setPriority(1);//设置优先级1~10
        cat.start();//开启线程
        System.out.println("main主线程启动子线程,main主线程不会阻塞,会继续执行,主线程结束不影响子线程,主线程名:" + Thread.currentThread().getName());
        Thread.sleep(2 * 1000);
        cat.interrupt();//中断线程
        cat.join();
        System.out.println("join相当于插队到main线程中来,cat线程执行完毕后才执行主线程");
    }
}

class Cat extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("喵喵喵~ " + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("线程被中断~");
            }
        }
    }
}

1.start() vs run()
//start真正启动新线程,将新线程从NEW->RUNNABLE
public class Start_ {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("running...");
        }, "thread1");
        System.out.println(thread.getState());
        thread.run();
        //thread.start();
        System.out.println(thread.getState());         
    }
}

2.sleep() vs yield()
sleep 会让当前线程从 Running 进入 Timed Waiting 状态(阻塞)
其它线程可以使用 interrupt 方法打断正在睡眠的线程
建议用 TimeUnit 的 sleep 代替 Thread 的 sleep 来获得更好的可读性

/*
A hint to the scheduler that the current thread is willing to yield
its current use of a processor. The scheduler is free to ignore this
 hint
*/
yield 会让当前线程从 Running 进入 Runnable 就绪状态态,然后调度执行其它线程
A hint to the scheduler,具体的实现依赖于操作系统的任务调度器

public class Sleep_ {
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            try {
                //Thread.sleep(2000);
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                System.out.println("会抛出 InterruptedException");
                e.printStackTrace();
            }
        }, "thread1");
        thread1.start();
        Thread.sleep(500);
        //其它线程可以使用 interrupt 方法打断正在睡眠的线程
        thread1.interrupt();
    }
}


3.Priority
java中规定线程优先级是1~10的整数,较大的优先级
能提高该线程被 CPU 调度的机率

public class Priority_yield {
    public static void main(String[] args) {
        Runnable task1 = () -> {
            int count = 0;
            for (;;) {
                System.out.println("---->1 " + count++);
            }
        };
        Runnable task2 = () -> {
            int count = 0;
            for (;;) {
                //Thread.yield();
                System.out.println(" ---->2 " + count++);
            }
        };
        Thread t1 = new Thread(task1, "t1");
        Thread t2 = new Thread(task2, "t2");
        // t1.setPriority(Thread.MIN_PRIORITY);
        // t2.setPriority(Thread.MAX_PRIORITY);
        t1.start();
        t2.start();
    }
}

4.join()
public class Join_ {
    private static int a = 0;
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            try {
                a = 10;
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "thread1");
        thread1.start();
        thread1.join();//Waiting for the finalization(结束) of a thread
        //thread1.join(1000);//有时效的 join
        System.out.println("a = " + a);
    }
}

5.interrupt
如果被打断线程正在 sleep,wait,join 会导致被打断
的线程抛出InterruptedException,isInterrupted=false
如果正在运行的线程、park的线程被打断,isInterrupted=true
LockSupport.park()LockSupport.unpark()实现线程的阻塞和唤醒
park()unpark()不会遇到Thread.suspend 和 Thread.resume所可能引发的死锁问题
信号量permit默认是0,累加上限是1park()消费permit,unpark()生成permit
interrupt()会使得中断状态为true,并调用unpark
如果打断标记已经是 true, 则 park 会失效,可以使用 Thread.interrupted() 清除打断状态

interrupt()interrupted()isInterrupted()方法详解
interrupt():中断线程,sleep,wait,join 会导致被打断
的线程抛出InterruptedException,正在运行的线程只是给线程设置一个中断标志,线程仍会继续运行
interrupted():测试当前线程是否被中断,并清除中断状态
isInterrupted():测试此线程是否被中断

6.过时的方法 stop()停止线程、suspend()挂起线程、resume()恢复线程,容易破坏同步代码块,造成线程死锁

释放锁:
1.同步方法、同步代码块正常执行结束,或遇到returnbreak
2.同步方法、同步代码块异常结束,出现ErrorException
3.调用wait()方法,当前线程暂停执行并释放锁

不释放锁:
1.调用sleep()yield()方法,当前线程暂停执行并不释放锁
2.线程执行同步代码块时,其他线程调用该线程的suspend()方法将线程挂起,该线程不释放锁。
提示:避免使用suspend()resume()控制线程,方法不再推荐使用
//synchronized线程同步
可在用在方法上(同步方法)、代码块(同步代码块),要求多个线程的锁对象是同一个
private synchronized static void sell() {
} //同步方法(静态)的锁对象默认为 当前类.class
private synchronized void sell() {
} //同步方法(非静态)的锁对象默认为 this
synchronized (对象) {
	//同步代码块
} 

//下面代码存在问题,不能完成互斥同步,原因:同步方法(非静态)的锁不是同一个对象
public class Syncronized_ {
    public static void main(String[] args) {
        
        Cat cat1 = new Cat();
        cat1.start();

        Cat cat2 = new Cat();
        cat2.start();
    }
}

class Cat extends Thread {
    static int ticketNum = 10;
    static boolean loop = true;

    @Override
    public void run() {
        while (loop) {
            sell();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized void sell() {
        if (ticketNum > 0) System.out.println(Thread.currentThread().getName() + "卖票:" + ticketNum--);
        else loop = false;
    }
}

修改如下:
方式一:同步方法(静态)的锁对象默认为 当前类.class
private synchronized static void sell() {
   if (ticketNum > 0) System.out.println(Thread.currentThread().getName() + "卖票:" + ticketNum--);
   else loop = false;
}

方式二:代码块上锁,指定同一个锁对象
private void sell() {
    synchronized (Syncronized_.class) {
        if (ticketNum > 0) System.out.println(Thread.currentThread().getName() + "卖票:" + ticketNum--);
        else loop = false;
    }
}

方式三:同步方法(非静态)的锁对象默认为 this
public class Syncronized_ {
    public static void main(String[] args) {

        Cat cat = new Cat();
        new Thread(cat).start();
        new Thread(cat).start();
    }
}

class Cat implements Runnable {
    static int ticketNum = 10;
    static boolean loop = true;

    @Override
    public void run() {
        while (loop) {
            sell();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized void sell() {
        if (ticketNum > 0) System.out.println(Thread.currentThread().getName() + "卖票:" + ticketNum--);
        else loop = false;
    }
	/*private void sell() {
	    synchronized (this) {
	        if (ticketNum > 0) System.out.println(Thread.currentThread().getName() + "卖票:" + ticketNum--);
	        else loop = false;
	    }
	}*/
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值