多线程

package test5;

public class TestDeadLock implements Runnable {
    public int flag;
    
    private static Object o1 = new Object();
    private static Object o2 = new Object();

    public void run() {
        System.out.println("" + flag + "个线程");
        if (flag == 1) {
            synchronized (o1) {
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("线程" + flag + "结束");
                }
            }
        }
        
        if (flag == 2) {
            synchronized (o2) {
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println("线程" + flag + "结束");
                }
            }
        }
    }

    public static void main(String[] args) {
        TestDeadLock td1 = new TestDeadLock();
        TestDeadLock td2 = new TestDeadLock();
        td1.flag = 1;
        td2.flag = 2;
        Thread t1 = new Thread(td1);
        Thread t2 = new Thread(td2);
        t1.start();
        t2.start();

    }
}

进程中可以包含多个线程

并发:

多线程

并行:

多个CPU执行多个事情

1, 线程的概念

一个程序中的方法有几条执行路径, 就有几个线程

2, 线程的创建:

两种方式:

1, 继承Thread类

class TestThread extends Thread {......}

2, 实现Runnable接口, 然后作为参数传入到Thread类的构造方法中

class TestThread implements Runnable {......}

线程的启动:

调用线程类中的start()方法, 不能直接调用run()方法, 直接调用run()方法那叫方法调用, 不是启动线程

3, 线程常用方法

isAlive()

判断线程是否还活着, 调用start()之前和终止之后都是死的, 其他的都是活的

看图...

interrupt()

停止线程

getPriority()

setPriority()

设置优先级, 优先级的概念: 谁的优先级高, 谁执行的时间就多

Thread里面的默认优先级:

Thread.MIN_PRIORITY = 1

Thread.MAX_PRIORITY = 10

Thread.NORM_PRIORITY = 5

Thread.sleep()

将程序暂停一会

join()

合并线程

yield() 

线程的礼让

让出CPU执行其他线程

4, 线程同步

synchronized

wait()---简单了解

notify()---简单了解

notifyAll()---简单了解

进程中可以包含多个线程并发:多线程并行:多个CPU执行多个事情
1, 线程的概念一个程序中的方法有几条执行路径, 就有几个线程
2, 线程的创建:两种方式:1, 继承Thread类class TestThread extends Thread {......}2, 实现Runnable接口, 然后作为参数传入到Thread类的构造方法中class TestThread implements Runnable {......}
线程的启动:调用线程类中的start()方法, 不能直接调用run()方法, 直接调用run()方法那叫方法调用, 不是启动线程
3, 线程常用方法isAlive()判断线程是否还活着, 调用start()之前和终止之后都是死的, 其他的都是活的看图...interrupt()停止线程getPriority()setPriority()设置优先级, 优先级的概念: 谁的优先级高, 谁执行的时间就多Thread里面的默认优先级:Thread.MIN_PRIORITY = 1Thread.MAX_PRIORITY = 10Thread.NORM_PRIORITY = 5Thread.sleep()将程序暂停一会join()合并线程yield() 线程的礼让让出CPU执行其他线程
4, 线程同步synchronizedwait()---简单了解notify()---简单了解notifyAll()---简单了解

原文地址:https://www.cnblogs.com/F9801/p/9067295.html