Java线程知识回顾

创建线程的方法

继承Thread

public class Client {
    
    
    public static void main(String[] args) {
    
    
        MyThread myThread = new MyThread("线程1");
        myThread.start();
    }
}

class MyThread extends Thread {
    
    

    public MyThread(String name) {
    
    
        super(name);
    }

    @Override
    public void run() {
    
    
        System.out.println(this.getName() + "正在运行...");
    }
}

实现Runnable接口

public class Client {
    
    
    public static void main(String[] args) {
    
    
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.setName("线程1");
        thread.start();
    }
}

class MyRunnable implements Runnable {
    
    

    @Override
    public void run() {
    
    
        System.out.println(Thread.currentThread().getName() + "正在运行...");
    }
}

匿名内部类

public class Client {
    
    
    public static void main(String[] args) {
    
    
        Thread thread = new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                System.out.println(Thread.currentThread().getName() + "正在运行...");
            }
        });
        thread.setName("线程1");
        thread.start();
    }
}

线程睡眠

/**
* 睡眠
* @Param 睡眠时间 单位ms
*/
Thread.sleep(1000);

线程睡眠时间要适度!

线程参与

public class Client {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        Thread thread = new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                for (int i = 1; i <= 100; i++) {
    
    
                    System.out.println(Thread.currentThread().getName()
                            + "执行第" + i + "次");
                }
            }
        });
        System.out.println("主线程运行1");
        thread.start();
        // 参与1ms
        thread.join(1);
        System.out.println("主线程运行2");
    }
}

在这里插入图片描述

线程优先级

设定线程优先级仅仅在线程调度中有作用,并不意味着优先级高的线程先运行,仅仅说明在线程调度中有优先权;
Java中线程优先级范围为1~10的正整数,并有三个常量
Thread.MIN_PRIORITY   // 值为1
Thread.MAX_PRIORITY   // 值为10
Thread.NORM_PRIORITY  // 值为5 线程默认值

线程同步

使用synchronized关键字可实现线程同步,可保证一个资源不被同时访问
synchronized关键字可修饰成员方法、静态方法、代码块。
  • 修饰成员方法
private synchronized void getSalary(){
    
    
	// 方法体
}
  • 修饰静态方法
private synchronized static void getSalary(){
    
    
	// 方法体
}
  • 修饰代码块
synchronized(this) {
    
    
	// 代码块
}

范例:账户存取

线程通信

wait()  
线程等待
notify() 
唤醒一个正在等待的线程,此唤醒具有任意性。
notifyAll() 
唤醒所有正在等待的线程。

范例:生产者消费者问题

猜你喜欢

转载自blog.csdn.net/L333333333/article/details/104005971