Java线程(一)

来源:互联网 发布:mac卸载cuda 编辑:程序博客网 时间:2024/05/15 08:01

一、线程的基本概念

  • 线程是一个程序里面不同的执行路径
二、线程的实现
  • Java的线程是通过java.lang.Thread类来实现的
三、线程的创建
  • 实现Runnable接口
  • 继承Thread类
四、线程的启动
  • 调用Thread类的start()方法
五、实例
  • 实现Runnable接口来创建线程
    /*Thread1.java*/public class Thread1 {public static void main(String[] args) {//new一个线程类的对象runnable r = new runnable();//要启动一个线程,必须通过Thread类的start()方法,所以要new一个Thread对象Thread t = new Thread(r);//然后通过Thread的start()方法启动线程t.start();for(int i=0; i<100; i++) {System.out.println("Main: " + i);}}}//实现Runnable接口,jdk就知道了这是一个线程类class runnable implements Runnable{public void run() {for(int i=0; i<100; i++) {System.out.println("Runnable: " + i);}}}
  • 继承Thread类来创建线程
    /*Thread2.java*/public class Thread2 {public static void main(String[] args) {thread t = new thread();//启动线程t.start();for(int i=0; i<100; i++) {System.out.println("Main: " + i);}}}//继承Thread类创建线程class thread extends Thread {public void run() {for(int i=0; i<100; i++) {System.out.println("Thread: " + i);;}}}
六、线程状态转换
  • 创建 start() 就绪状态阻塞解除cpu调度阻塞状态运行状态导致阻塞的状态终止 
七、线程控制基本方法
  • 方法功能isAlive()判断线程是否还"活"着,即线程是否还未终止getPriority()获得线程的优先级数值setPriority()设置线程的优先级数值Thread.sleep()将当前线程睡眠指定毫秒数join() 调用某线程的该方法,将当前线程与该线程"合并",即等待该线程结束,再恢复当前线程的运行yield()让出cpu,当前线程进入就绪队列等待调度wait()让当前线程进入对象的wait poolnotify()
    notifyAll()唤醒对象的wait pool中的一个/所有等待线程
八、实例
  • 测试sleep()
    /*Sleep.java*/import java.util.Date;public class Sleep {public static void main(String[] args) {thread t = new thread();t.start();try {//当前线程(main线程)睡眠10秒Thread.sleep(10000);} catch (InterruptedException e) {//打断线程t的睡眠t.interrupt();}}}class thread extends Thread {public void run() {while(true) {System.out.println(new Date());try {sleep(1000);} catch (InterruptedException e) {return;}}}}

  • 测试join()
    /*Join.java*/public class Join {public static void main(String[] args) {thread t = new thread("t");t.start();try {t.join();} catch (InterruptedException e) {}for(int i=0; i<100; i++) {System.out.println("i am main thread");}}}class thread extends Thread {//给线程起一名字thread(String str) {super(str);}public void run() {for(int i=0; i<100; i++) {System.out.println("i am " + getName());try {sleep(1000);} catch (InterruptedException e) {return;}}}}

  • 测试yield()
    /*Yield.java*/public class Yield {public static void main(String[] args) {thread t1 = new thread(t1);thread t2 = new thread(t2);t1.start();t2.start();}}class thread extends Thread {thread(String str) {super(str);}public void run() {for(int i=0; i<100; i++) {System.out.println(getName() + ": " + i);if(i%10==0) {yield();}}}}

  • 测试priority()
    /*Priority.java*/public class Priority {Thread t1 = new Thread(new T1());Thread t2 = new Thread(new T2());t2.setPriority(Thread.NORM_PRIORITY + 3);t1.start();t2.start();}class T1 implements Runnable {public void run() {for(int i=0; i<100; i++) {System.out.println("T1: " + i);}}}class T2 implements Runnable {public void run() {for(int i=0; i<100; i++) {System.out.println("T2: " + i);}}}

1 0
原创粉丝点击