多线程创建方式有两种
方式1:
调用方法
public static void run(){ //获取当前线程名称 String name=Thread.currentThread().getName(); System.out.println(name); MyThread th1=new MyThread("线程1"); MyThread th2=new MyThread("线程2"); //开始执行,虚拟机调用线程run方法 th1.start(); th2.start(); }
线程类:
/* * 实现1: * 1.继承Thread类。 * 2.实现类的run方法。 * 3.启动新线程直接new。 * */ public class MyThread extends Thread { public MyThread() { } //给线程命名 public MyThread(String name) { super(name); } @Override public void run() { for (int i=0;i<100;i++){ System.out.println(getName()+":"+i); try { /* *sleep使线程休眠100ms再执行 * * sleep执行策略: * 1.遇到sleep线程移出执行线程。 * 2.加入事件队列。 * 3.定时时钟会一段时间检查一次,如果到执行时间。 * 4.加入执行队列。 * 5.根据线程调度算法,分配给该线程执行。 */ Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }
方式二
调用方法:
public static void runnable(){ MyRunnable myRunnable=new MyRunnable(); Thread th1=new Thread(myRunnable,"线程1"); Thread th2=new Thread(myRunnable,"线程2"); Thread th3=new Thread(myRunnable,"线程3"); th1.start(); th2.start(); th3.start(); }
实现接口:
/* * 实现2: * 1.实现Runnable接口 * 2.实现里面的run方法 * * 优点:避免了Java单继承的局限性 * 适合多个相同程序的代码去处理同一个资源的情况,把线程和程序的代码、数据有效分离,较好的体现了面向对象的设计思想 * */ public class MyRunnable implements Runnable { @Override public void run() { for (int i=0;i<100;i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } }
生命周期:
多线程方法:
1.设置线程名
public static void run(){ //获取当前线程名称 String name=Thread.currentThread().getName(); System.out.println(name); //需要构造函数添加 MyThread th1=new MyThread("线程1"); MyThread th2=new MyThread("线程2"); //开始执行,虚拟机调用线程run方法 th1.start(); th2.start(); } public static void setName(){ MyThread th1=new MyThread(); MyThread th2=new MyThread(); th1.setName("线程1"); th2.setName("线程2"); th1.start(); th2.start(); }
2.priority优先级
/* * CPU的线程两种调度模型: * 分时调度模型:所有线程轮流使用 CPU 的使用权,平均分配每个线程占用 CPU 的时间片 * 抢占式调度模型:优先让优先级高的线程使用 CPU,如果线程的优先级相同,那么会随机选择一个,优先级高的线程获取的 CPU 时间片相对多一些 * * Java使用的是抢占式调度模型 * * 线程默认优先级是5;线程优先级的范围是:1-10 线程优先级高仅仅表示线程获取的CPU时间片的几率高,但是要在次数比较多,或者多次运行的时候才能看到你想要的效果 * */ public static void priority(){ MyThread th1=new MyThread("线程1"); MyThread th2=new MyThread("线程2"); MyThread th3=new MyThread("线程3"); //获取线程优先级 System.out.println(th1.getPriority()); //设置线程优先级 th1.setPriority(10); th2.setPriority(5); th3.setPriority(1); //开始执行,虚拟机调用线程run方法 th1.start(); th2.start(); th3.start(); }
3.join阻塞
/* * join:会等待线程1执行完成才会执行后面,相当于阻塞主线程 * */ public static void join() throws InterruptedException { MyThread th1=new MyThread("线程1主线程"); MyThread th2=new MyThread("线程2"); MyThread th3=new MyThread("线程3"); //开始执行,虚拟机调用线程run方法 th1.start(); //阻塞线程 th1.join(); th2.start(); th3.start(); }
4.daemon:守护线程
/* * daemon:守护线程 * 特点:主线程执行完成,守护线程也结束 * */ public static void daemon(){ MyThread th1=new MyThread("线程1"); MyThread th2=new MyThread("线程2"); //设置为守护线程 th1.setDaemon(true); th2.setDaemon(true); th1.start(); th2.start(); for (int i=0;i<10;i++){ System.out.println(Thread.currentThread().getName()+":"+i); } }