线程
分为并发和并程
线程创建的第一种方法:
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类所具有的优势:
- 适合多个相同的程序代码的线程去共享同一个资源。
- 可以避免java中的单继承的局限性。
- 增加程序的健壮性,实现解耦操作,代码可以被多个线程共享,代码和线程独立。
匿名内部类:
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()`:释放锁。