- java语言提供了并发机制,每一个线程执行一个任务,并且与其他的线程一起执行,这种机制称为多线程
- 实现线程的两种方式:继承Thread类和实现Runnable接口,实际上底层代码Thread类也是实现了Runnable接口的run函数
public class ThreadTest extends Thread {
private int i = 1;
@Override
public void run(){
while (i < 20){
System.out.println(i);
System.out.println(currentThread());
i ++;
}
}
public static void main(String[] args){
System.out.println(currentThread());
Thread thread1 = new ThreadTest();
Thread thread2 = new ThreadTest();
thread1.start();
thread2.start();
}
}
public class RunnableDemo implements Runnable {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println();
}
}
public static void main(String[] args){
Runnable runnable1 = new RunnableDemo();
Runnable runnable2 = new RunnableDemo();
Thread thread1 = new Thread(runnable1);
System.out.println(thread1);
Thread thread2 = new Thread(runnable2);
System.out.println(thread2);
thread1.start();
thread2.start();
}
}
- 线程的生命周期:一共七种状态:出生、就绪、运行、等待、休眠、阻塞、死亡
wait()
notify()
notifyAll()
sleep()
try {
Thread.sleep(100);
} catch (InterruptedException e){
e.printStackTrace();
}
thread.join()
thread.intercept()
- 线程的优先级:如果很多线程处于就绪的状态,那么系统会根据线程的优先级决定哪个线程执行,并不是说哪个线程的优先级高就优先执行,而是执行的概率高
thread.setPriority(1);
- 线程同步:为避免两个线程同时操作系统的资源导致数据出现异常
synchronized (""){}
public synchronized void doit() {
}