版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34195441/article/details/86236748
1、一般线程创建与调用
1)继承thread类,重写run()方法
package com.hpu.thread;
/**
* 线程是CPU调度和执行的最小单元,进程有独立的运行内存空间,线程占用的是进程的空间
* 一个进程会有一个或者多个线程,线程是通过抢占cpu的时间片来执行的,谁抢到谁执行
* 创建线程:继承Thread类、重写run()方法
* 无论是主线程还是自定义线程,执行顺序是随机的
* @author Administrator
*/
public class TestThread {
//main方法中的线程是主线程
public static void main(String[] args) {
//实例化自定义线程
MyThread myThread = new MyThread();
MyThread2 myThread2 = new MyThread2();
MyThread myThread3 = new MyThread();
MyThread myThread4 = new MyThread();
//myThread.run();
//给线程自定义名称
myThread.setName("线程一号");
myThread2.setName("线程二号");
//通过strart方法开启线程,会自动调用线程的run()方法
myThread.start();
myThread3.start();
myThread2.start();
myThread4.start();
System.out.println(Thread.currentThread().getName()+"~~~");
}
}
class MyThread extends Thread{
public void run(){
//获取当前线程的名称
String currentName = Thread.currentThread().getName();
System.out.println(currentName+"线程创建并运行,抢手机中。。。");
}
}
class MyThread2 extends Thread{
public void run(){
String currentName = Thread.currentThread().getName();
System.out.println(currentName+"线程创建并运行,二次出售了。。。");
}
}
2)开启线程的第二种方式:实现runnable()接口
package com.hpu.thread;
//开启线程的第二种方式:实现runnable接口
public class TestThread3 {
public static void main(String[] args){
for(int i=0;i<4;i++){
new Thread(new Runnable(){
public void run(){
System.out.println(Thread.currentThread().getName());
}
}).start();
}
// th.start();
}
}
2、线程的优先级
package com.hpu.thread;
/**
* 控制线程的优先级
* 线程默认的优先级是5,线程优先级高,并不意味着一定能抢到cpu的时间片,只是抢到的概率大一些
* 线程有五种状态:
* 新建状态:new 线程
* 就绪状态:执行start方法,内部调用run方法时,调用run()方法并不代表会立即执行,因为还有可能在抢时间片
* 运行状态:run()方法执行
* 阻塞方法:线程的sleep()方法执行时,线程会处于阻塞状态,阻塞状态结束会进入就绪状态,接着抢时间片
* 死亡状态:线程运行完结束,stop方法手动停止(用的比较少)
* @author Administrator
*
*/
public class TestPriority {
public static void main(String[] args) {
MyThread th1 = new TestPriority().new MyThread();
MyThread th2 = new TestPriority().new MyThread();
//设置优先级
th1.setPriority(10);
th2.setPriority(1);
//开启线程
th1.start();
th2.start();
}
public class MyThread extends Thread{
//重写run()方法
public void run(){
for(int i=0;i<10;i++){
if(i==5){
//线程休眠5秒
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"---"+i);
}
}
}
}
3、内部类定义线程
package com.hpu.thread;
public class TestThread2 {
public static void main(String[] args) {
for(int i=0;i<2;i++){
//实例化并开启线程
new TestThread2().new MyThread().start();
}
}
/**
* 内部类定义线程
* 循环中执行的线程也会被抢占cpu
*/
public class MyThread extends Thread{
public void run(){
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"---"+i);
}
}
}
}