java多线程
1.什么是线程:
我们先来了解一下什么是线程。
要了解线程先得知道什么是进程,进程是程序的基本执行实体,就是说程序是由不同的进程来实现的,我们打开资源管理器就可以看到各种进程,程序本身只是指令、数据及其组织形式的描述,进程才是程序(那些指令和数据)的真正运行实例。
但是进程却不是最基本的程序运行单位,可以理解为线程的容器,线程是独立调度和计算机资源分配的基本单位。
线程(英语:thread)是操作系统能够进行运算调度的最小单位。
2.线程的创建:
class Mythread extends Thread{
public void run(){
System.out.println(getName()+":该线程正在运行");
}
}
public class ThreadTest {
public static void main(String[] args) {
System.out.println("主线程1");
Mythread mt=new Mythread();
mt.start();
System.out.println("主线程2");
}
}
class MyThread2 extends Thread {
public MyThread2(String name) {
super(name);
}
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(getName() + "正在运行第" + i + "次");
}
}
}
public class ThreadTest2 {
public static void main(String[] args) {
MyThread2 mt1 = new MyThread2("线程1");
MyThread2 mt2 = new MyThread2("线程2");
mt1.start();
mt2.start();
}
}
package threadDemo;
//通过实现Runnable接口来创建线程
class PrintThread implements Runnable {
public void run() {
int i = 0;
while (i < 10) {
System.out.println(Thread.currentThread().getName() + "正在执行" + i);
i++;
}
}
}
public class TreadDemo3 {
public static void main(String[] args) {
PrintThread pr = new PrintThread();
Thread tm1 = new Thread(pr, "线程1");
Thread tm2 = new Thread(pr, "线程2");
tm1.start();
tm2.start();
}
}
3.线程的状态:
stop方法终止运行,进入终止态
😪sleep方法(静态方法 在run()中使用):
//通过实现Runnable接口来创建线程
//通过Thread.sleep(ms)方法实现
class PrintThreadSleep implements Runnable {
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println(Thread.currentThread().getName() + "正在执行" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadTest4 {
public static void main(String[] args) {
PrintThreadSleep pr = new PrintThreadSleep();
Thread tm1 = new Thread(pr, "线程1");
Thread tm2 = new Thread(pr, "线程2");
tm1.start();
tm2.start();
}
}
🕹jion方法(对象使用)
class Mythread3 extends Thread {
public void run() {
for (int i = 1; i <= 300; i++) {
System.out.println(getName() + ":该线程正在运行" + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadTest5 {
public static void main(String[] args) {
Mythread3 mt = new Mythread3();
mt.start();
try {
mt.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 1; i <= 300; i++) {
System.out.println("主线程正在运行" + i);
}
}
}
4.线程优先级
class MyThread4 extends Thread {
private String name;
public MyThread4(String name) {
this.name = name;
}
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println(name + "正在运行" + i);
}
}
}
public class ThreadTest6 {
public static void main(String[] args) {
MyThread4 mt1 = new MyThread4("线程1");
MyThread4 mt2 = new MyThread4("线程2");
mt1.setPriority(1);
// mt1.setPriority(Thread.MIN_PRIORITY);
mt2.setPriority(10);
// mt2.setPriority(Thread.MAX_PRIORITY);
mt1.start(); // 结果是随机的 虽然mt2进程优先级高,但是操作系统先来先服务
// mt2还未到来时可能mt1先启动已经执行完了
mt2.start();
}
}