系统相关
首页 > 系统相关> > 进程和线程

进程和线程

作者:互联网

1.进程

进程:是正在运行的程序

2.线程

线程:是进程中的单个顺序控制流,是一条执行路径
多线程的实现方式一:
通过继承Thread类的方式实现多线程
public class MyThread extends Thread{
    public MyThread(){}
    public MyThread(String name){
        super(name);
    }
    
    @Override
    public void run(){
        for(int i=0;i<100;i++){
            System.out.println(getName()+":"+i);
        }
    }
}
public class MyRunnableDemo{
    public static void main(String[] args){
        //MyThread my1 = new MyThread();
        //MyThread my2 = new MyThread();
        MyThread my1 = new MyThread("线程1");
        MyThread my2 = new MyThread("线程2");
        
        my1.start();
        my2.start();
    }
}

image

线程优先级

线程有两种调度模型:
Thread 类中设置和获取线程优先级的方法:
线程优先级的常量:
线程控制:

image

image

线程生命周期:

image

多线程的实现方式二:
通过实现Runnable接口的方式实现多线程
public class MyRunnable implements Runnable{
    @Override
    public void run(){
        for(int i=0;i<100;i++){
            System.out.println(Thread.currentThread().getName()+":"+i);
        }
    }
}
public class MyRunnableDemo{
    public static void main(String[] args){
        MyRunnable my = new MyRunnable();
        
        //Thread t1 = new Thread(my);
        //Thread t2 = new Thread(my);
        Thread t1 = new Thread(my,"线程1");
        Thread t2 = new Thread(my,"线程2");
        
        t1.start();
        t2.start();
    }
}
多线程实现的两种方式的区别:

相比继承Thread类,实现Runnable接口的好处

3.线程同步

(1)同步代码块

image

(2)同步方法

image

(3)线程安全的类

image

(4)Lock锁

Lock实现提供比使用synchronized方法和语句可以获得更广泛的锁定操作

Lock中提供了获取锁和释放锁的方法:

Lock是接口不能直接实例化,这里采用它的实现类ReentrantLock来实例化

ReentrantLock的构造方法:

public class SellTicket implements Runnable{
    private int tickets = 100; //票数
    private Lock lock = new ReentrantLock();
    
    @Override
    public void run(){
        while(true){
            try{
                lock.lock();
                if(tickets>0){
                    try{
                        Thread.sleep(100);
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"正在出售第"+tickets+"张票");
                    tickets--;
                }
            }finally{
            	lock.unlock();
            }
        }
    }
}
public class SellTicketDemo{
    public static void main(String[] args){
        SellTicket st = new SellTicket();
        
        Thread t1 = new Thread(st,"窗口1");
        Thread t2 = new Thread(st,"窗口2");
        Thread t3 = new Thread(st,"窗口3");
        
        t1.start();
        t2.start();
        t3.start();
    }
}

标签:优先级,Thread,MyThread,线程,进程,new,public
来源: https://www.cnblogs.com/onesun/p/15811318.html