1.线程和多线程简介
2.创建线程的两种方法
3.线程的生命周期
4.线程的优先级
5.线程同步
1.1
进程的简介:进程可以简单的理解为计算机中正在运行的程序,比如 正在运行的qq、暴风影音、qq管家等等。每一个独立运行的程序都可以称之为一个进程。
线程:线程就是进程的细化。在一个程序中,线程就是程序可执行的一个路径,一个程序可以由多个线程并发运行,也就是说该程序支持多线程;
2.1创建线程的两种方法
第一种就是让一个类就继承 Thread类。重写run 用该类的实例调用start方法。开启线程
public class MyThread2 extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
}
}
public class Test3 {
public static void main(String[] args) {
//开启线程
new Thread(new MyRunnable()).start();
}
}
线程的生命周期有六个状态
1.NEW---新建的状态
2.RUNNABLE---可以运行的状态
3.BLOCKED---阻塞状态
4.WAITING---等待状态
5.TIMED_WAITING---超时等待的状态
6.TERMINATED---终止状态
给大家演示一个线程休眠的一个例子
public class MyThread extends Thread {
/**
* 每隔一秒输出 1.2.3.4.5.6
*/
public void run() {
for(int i=1;i<7;i++){
System.out.println(i);
try {
//休眠1秒中
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
Thread.yield这个方法 暂停当前正在执行的线程对象 去执行其他优先级高的线程
5.线程的同步
线程的同步可以有三种方式
synchronized同步代码块
package com.edu118.test27;
public class MyRuunable1 implements Runnable{
//车票
private int tickets =1000;
//同步代码快来实现10个窗口打印1000张车票
@Override
public void run() {
while(true){
//锁住当前对象,是个线程中都是同一个一个对象 MyRuunable1 runnable = new MyRuunable1();
synchronized(this){
if(tickets>0){
System.out.println(Thread.currentThread().getName()+"在打印第"+tickets+"车票");
tickets--;
}else{
System.out.println(Thread.currentThread().getName()+"已售空");
break;
}
}
}
}
}
public class Test1 {
public static void main(String[] args){
MyRuunable1 runnable = new MyRuunable1();
//开启10个线程
for(int i=1;i<11;i++){
new Thread(runnable,"窗口"+i).start();
}
}
}
synchronized同步方法
package com.edu118.test27;
public class MyRunnable2 implements Runnable{
private static int tickets=1000;
private String names;
@Override
public void run() {
//调用synchronized修饰的同步方法 调用该方法的都是同一个对象。实现了线程同步的功能
while(this.printTickets());
}
//打印车票
public synchronized boolean printTickets(){
if(tickets>0){
System.out.println(Thread.currentThread().getName()+"正在打印第"+tickets+"车票");
tickets--;
return true;
}else{
System.out.println(Thread.currentThread().getName()+"已经售空");
return false;
}
}
}
Test2
lock对象锁
public class Test2 {
public static void main(String[] args){
MyRunnable2 runnable = new MyRunnable2();
//开启是个线程
for(int i=1;i<11;i++){
new Thread(runnable,"窗口"+i).start();
}
}
}