世界上本没有多线程,cpu故意在各个线程中跳转,就假装有了多线程
测试的时候语句少的一下被执行完,要增加多点语句才能测试出来恰恰说明了这个原理
线程的实现由两种方法
1)继承Thread,然后重写run方法,(不能漏掉public
class SpackA extends Thread{ SpackA a=new SpackA();
2)运用Thread(Runnable target),run方法改在Runnable接口里面实现
class SpackA implements Runnable{ Thread a=new Thread(new SpackA());
线程有优先级,默认是5,既是Thread.NORM_PRIORITY,最大Thread.MIN_PRIORITY,最小Thread.MAX_PRIORITY
setPriority()//在try语句中执行 getPriority()
一些知识
sleep(int millsecond)要在try-catch块中进行
isAlive()可以检测线程是否生存,(run方法开始运行到结束就是生存的)
类方法currentThread()返回当前调用的线程
线程不要重新赋值,因为旧的线程不会被垃圾回收机制回收,还会继续发挥作用
interrupt()可以重新激活sleep的程序,在sleep的try-catch块里面会发出异常
import java.io.*; import java.util.Scanner; import java.sql.*;public class Test {public static void main(String args[]){demo demo1=new demo();demo1.student=new Thread(demo1);demo1.teacher=new Thread(demo1);demo1.student.start();demo1.teacher.start();} }class demo implements Runnable{Thread student,teacher;@Overridepublic void run() {// TODO 自动生成的方法存根if(Thread.currentThread()==student){System.out.println("sleep");try {student.sleep(10000);} catch (InterruptedException e) {// TODO 自动生成的 catch 块System.out.println("ririri");}System.out.println("shangke");}else if(Thread.currentThread()==teacher){for(int i=0;i<3;i++){System.out.println("upup");}student.interrupt();}}}