java - 线程

线程创建方法

继承Thread类创建线程
// 1.创建继承Thread类
calss ThreadChildren extends Thread {
	@Override
	public void run(){
		// 2.重写run()方法
		// 添加具体实现内容
		// this.getName()
	}
}
public static void main(String[] args) {
	// 3.创建继承Thread类的类的对象
	ThreadChildren t1 = new ThreadChildren();
	t1.setName("线程")
	// 4.启动线程
	t1.start()        
}

start() :开启当前线程,调用run()。在当前线程开启时不能同时再次开启当前线程
run() :重写Thread类中的run()方法,实现所需功能

线程的一些方法

getName() :获取当前线程名称
setName() :设置当前线程名称
currentThread() :静态方法,返回房前代码的线程
yield() :释放当前CPU执行权
join() :在一个线程中调用另一个线程的join(),这个线程会进入阻塞状态,等另一个线程执行后这个线程才会继续执行
sleep(time) :让当前线程阻塞指定时间
isAlive() :判断当前线程是否存活

线程的优先级

MIN_PRIOPIIY : 1
NORM_PRIORITY : 5
MAX_PRIORITY : 10

getPriority() 获取当前线程优先级
setPriority() 设置当前线程优先级
高优先级线程抢占低优先级线程,只是概率,不一定一定高优先级先执行

实现Runnable接口创建线程
// 1.创建一个实现Runable接口的类
class RunnableTest implements Runable{
	@Override
	void run(){
		// 添加具体实现内容
	}
}
public static void main(String[] args) {
	// 2.创建实现Runnable类的对象
	RunnableTest r = new RunnableTest();
	// 3.将此对象作为参数传递到Thread的构造器中,创建Thread类的对象
	Thread t = new Thread(r);
	// 4.通过Thread类的对象调用start()
	t.start();
}

线程安全

1.同步代码块

synchronized(同步监视器){
     需要同步的代码块 ,即多个线程同时操作的代码
  }

  同步监视器:俗称“锁”,锁可以是任何一个类的对象,同步时多个线程必须使用一个锁

	public static void main(String[] args) {
        ThreadTest t1 = new ThreadTest();
        ThreadTest t2 = new ThreadTest();
        t1.start();
        t2.start();
		
		ThreadRun tr = new ThreadRun();
		Thread t3 = new Thread(tr);
		Thread t4 = new Thread(tr);
		t3.start();
		t4.start(); 
    }
	class ThreadTest extend Thread{
		static int num = 100;
		static Object o = new Object();
		static Arg a = new Arg();
		@Override
		void run(){
			// synchronized(o){
			// synchronized(a){
			synchronized(ThreadTest.calss){
			// ThreadTest.calss 类本身
				while (true){
	                if(num > 0){
	                    System.out.println(Thread.currentThread().getName() + ":" +  num);
	                    num --;
	                }
	            }
			}
		}
	}
	class ThreadRun implements Runnable{
		int num = 100;
		@Override
		void run(){
			synchronized(this){
				while (true){
	                if(num > 0){
	                    System.out.println(Thread.currentThread().getName() + ":" +  num);
	                    num --;
	                }
	            }
			}
		}
	}
	class Arg{}

2.同步方法

synchronized 方法名(){
  需要同步的代码块 需要同步的代码块
 }

 同步方法扔涉及同步监视器,只是不需要显示声明
  非静态方法,同步监视器为this
  静态方法,同步监视器为当前类本身

public static void main(String[] args) {
        ThreadTest t1 = new ThreadTest();
        ThreadTest t2 = new ThreadTest();
        t1.start();
        t2.start();
		
		ThreadRun tr = new ThreadRun();
		Thread t3 = new Thread(tr);
		Thread t4 = new Thread(tr);
		t3.start();
		t4.start(); 
    }
	class ThreadTest extend Thread{
		static int num = 100;
		@Override
		void run(){
			while (true){
	            show();
	        }
		}
		static synchronized void show(){
			if(num > 0){
	           System.out.println(Thread.currentThread().getName() + ":" +  num);
	              num --;
	           }
		}
	}
	class ThreadRun implements Runnable{
		int num = 100;
		@Override
		void run(){
			while (true){
	            show();
	        }
		}
		synchronized void show(){
			if(num > 0){
	           System.out.println(Thread.currentThread().getName() + ":" +  num);
	           num --;
	        }
		}
	}

3.Lock锁
Lock是一个接口,ReentrantLock类实现的Lock接口

public static void main(String[] args) {
        ThreadTest t1 = new ThreadTest();
        ThreadTest t2 = new ThreadTest();
        t1.start();
        t2.start();
		
		ThreadRun tr = new ThreadRun();
		Thread t3 = new Thread(tr);
		Thread t4 = new Thread(tr);
		t3.start();
		t4.start(); 
    }
	class ThreadTest extend Thread{
		static int num = 100;
		// 创建Lock接口实现类的对象
    	private static ReentrantLock lock = new ReentrantLock();
		@Override
		void run(){
			while (true){
	            try {
                //调用锁定lock()
                lock.lock();
                if (num > 0) {
                    System.out.println(Thread.currentThread().getName() + ":" + num);
                    num--;
                }else{
                    break;
                }
            }finally{
                // 调用解锁的方法unlock()
                lock.unlock();
            }
	        }
		}
		
	
线程安全
  • wait():执行此方法,当前线程进入阻塞状态,并释放同步监视器
  • natify():执行此方法,会唤醒被wait的一个线程,如果又多个线程被wait,就唤醒优先级搞的线程
  • natidyALL():执行此方法,会唤醒被wait的所有线程
  • wait(),natify(),natifyAll()三个方法必须使用在同步代码块或同步方法种
  • wait(),natify(),antifyAll()三个方法的调用者必须是同步代码块或同步方法中的同步监视器
  • wait(),natify(),antifyAll()三个方法定义在java.lang.Object类中
class Number implements Runnable{
    private int num = 1;
    @Override
    public void run() {
            while(true){
                synchronized(this){
                    //唤醒被阻塞的线程
                    notify();
                    if(num <= 100){
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + ":" + num);
                        num ++;
                        try {
                            // 使得调用wait()的线程进入阻塞
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else{
                        break;
                    }
                }
            }
    }
}
public class CommunicationTest {
    public static void main(String[] args) {
        Number n = new Number();
        Thread t1 = new Thread(n);
        Thread t2 = new Thread(n);
        t1.start();
        t2.start();
    }


}
实现Callable接口
// 1.创建实现Callable接口的实现类
class ThreadCallable implements Callable{
	// 2.重写call
	@Override
	public Object call() throws Exception{
		int sum = 0;
        for (int i = 1; i <= 100; i++) {

            if(i % 2 == 0){
                System.out.println(i);
                sum += i;
            }
        }
        return sum;
	}
}

public class CallableTest {
    public static void main(String[] args) {
        //3.创建Callable实现类的对象
        NumThread n = new NumThread();
        //4.将Callable实现类对象作为参数传递到FutrueTask构造器中,创建FutureTask的对象
        FutureTask futureTask = new FutureTask(n);
        // 5.将FutureTask对象传递到Thread构造器中,创建Thread对象,调用start();
        new Thread(futureTask).start();

        try {
            // get()返回值即为FutureTask构造器参数Callable实现类重写的的call()的返回值
            Object sum = futureTask.get();
            System.out.println(sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
线程池
class numberThread implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){
                System.out.println(i);
            }
        }
    }
}
class numberThread1 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 != 0){
                System.out.println(i);
            }
        }
    }
}
public class ThreadPool {
    public static void main(String[] args) {
        // 1.提供指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);

        ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;

        //设置线程池的属性
        service1.setCorePoolSize(15);

        // 2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口的实现类的对象
        numberThread nt = new numberThread();
        numberThread1 nt1 = new numberThread1();
        service.execute(nt);//适合使用于Runnable
        service.execute(nt1);//适合使用于Runnable
//        service.submit();//适合使用于Callable

        // 3.关闭线程池
        service.shutdown();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值