day17_线程创建、线程同步、线程状态

线程
分为并发和并程
线程创建的第一种方法:
1.定义一个类继承Thread类
2.重写run方法
3开启线程
使用方法:
创建子类对象
调用Thread类的start/run还是单线程

public class MyThread extends Thread {
	/**
	 * 重写run方法,完成该线程执行的逻辑
	 */
	@Override
	public void run() {
		for (int i = 0; i < 200; i++) {
			System.out.println("自定义线程正在执行!"+i);
		}
	}
}
public static void main(String[] args) {
    //创建自定义线程对象
    MyThread mt = new MyThread();
    //开启新线程
    mt.start();
    //在主方法中执行for循环
    for (int i = 0; i < 200; i++) {
    	System.out.println("main线程!"+i);
    }
}

通过Thread.currentThread().getName();
返回当前栈的线程名
在重写的run方法中写这个
在创建对象后可以用setname设置线程名

第二种方法
继承Runnable后重写Run方法
创建对象后 subrun gg=new subrun(50);创建一条线程,但是不会运行
Thread ggg=newThred(gg)要通过这个才能运行
ggg.start();

public class MyRunnable implements Runnable{
	public void run() {
		for (int i = 0; i < 20; i++) {
			System.out.println(Thread.currentThread().getName()+" "+i);
		}
	}
}
public class Demo {
    public static void main(String[] args) {
        //创建自定义类对象  线程任务对象
        MyRunnable mr = new MyRunnable();
        //创建线程对象
        Thread t = new Thread(mr);
        t.start();
        for (int i = 0; i < 20; i++) {
            System.out.println("main " + i);
        }
    }
}

实现Runnable接口比继承Thread类所具有的优势:

  1. 适合多个相同的程序代码的线程去共享同一个资源。
  2. 可以避免java中的单继承的局限性。
  3. 增加程序的健壮性,实现解耦操作,代码可以被多个线程共享,代码和线程独立。

匿名内部类:

public class NoNameInnerClassThread {
   	public static void main(String[] args) {	   	
//		new Runnable(){
//			public void run(){
//				for (int i = 0; i < 20; i++) {
//					System.out.println("张宇:"+i);
//				}
//			}  
//	   	}; //---这个整体  相当于new MyRunnable()
        Runnable r = new Runnable(){
            public void run(){
                for (int i = 0; i < 20; i++) {
                  	System.out.println("张宇:"+i);
                }
            }  
        };
        new Thread(r).start();

        for (int i = 0; i < 20; i++) {
          	System.out.println("费玉清:"+i);
        }
   	}
}

延时启动:
sleep
Thread.sleep(1000)延时1秒运行

设置线程优先级:

public static final int MIN_PRIORITY   //1 最低优先级
public static final int NORM_PRIORITY  //5 默认优先级
public static final int MAX_PRIORITY   //10 最大优先级

守护线程:
用户线程执行完守护线程就停止
gg.setDaemon(true);

插队
gg.join
此线程先运行其他线程等待,运行完后其他线程争先运行

线程安全
同步防止同一个方法多个线程进入导致错误
synchronized(同步锁){
需要同步操作的代码
}
注意:在任何时候,最多允许一个线程拥有同步锁,谁拿到锁就进入代码块,其他的线程只能在外等着(BLOCKED)

public synchronized void method(){
   	可能会产生线程安全问题的代码
}

Lock锁:

- `public void lock() `:加锁。
- `public void unlock()`:释放锁。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值