A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© pi408637535 中级黑马   /  2015-7-15 19:03  /  390 人查看  /  7 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

Java 线程很简单就三种状态:就绪,运行,空闲 (进程是分配资源的基本单位,线程在进程中运行)
Java要运行线程,这个类要么是继承Thread,要么Runnable。(我们一般选择接口,因为Java是单继承模式)
Java的线程是有优先级的。//高级 分的时间片多 反之亦然
两个实例
Thread继承:
  1. // 通过继承 Thread 创建线程
  2. class NewThread extends Thread {
  3. NewThread() {
  4. // 创建第二个新线程
  5. super("Demo Thread");
  6. System.out.println("Child thread: " + this);
  7. start(); // 开始线程
  8. }

  9. // 第二个线程入口
  10. public void run() {
  11. try {
  12. for(int i = 5; i > 0; i--) {
  13. System.out.println("Child Thread: " + i);
  14. // 让线程休眠一会
  15. Thread.sleep(50);
  16. }
  17. } catch (InterruptedException e) {
  18. System.out.println("Child interrupted.");
  19. }
  20. System.out.println("Exiting child thread.");
  21. }
  22. }

  23. public class ExtendThread {
  24. public static void main(String args[]) {
  25. new NewThread(); // 创建一个新线程
  26. try {
  27. for(int i = 5; i > 0; i--) {
  28. System.out.println("Main Thread: " + i);
  29. Thread.sleep(100);
  30. }
  31. } catch (InterruptedException e) {
  32. System.out.println("Main thread interrupted.");
  33. }
  34. System.out.println("Main thread exiting.");
  35. }
  36. }
复制代码
Runnable 接口:
  1. // 创建一个新的线程
  2. class NewThread implements Runnable {
  3. Thread t;
  4. NewThread() {
  5. // 创建第二个新线程
  6. t = new Thread(this, "Demo Thread");
  7. System.out.println("Child thread: " + t);
  8. t.start(); // 开始线程
  9. }

  10. // 第二个线程入口
  11. public void run() {
  12. try {
  13. for(int i = 5; i > 0; i--) {
  14. System.out.println("Child Thread: " + i);
  15. // 暂停线程
  16. Thread.sleep(50);
  17. }
  18. } catch (InterruptedException e) {
  19. System.out.println("Child interrupted.");
  20. }
  21. System.out.println("Exiting child thread.");
  22. }
  23. }

  24. public class ThreadDemo {
  25. public static void main(String args[]) {
  26. new NewThread(); // 创建一个新线程
  27. try {
  28. for(int i = 5; i > 0; i--) {
  29. System.out.println("Main Thread: " + i);
  30. Thread.sleep(100);
  31. }
  32. } catch (InterruptedException e) {
  33. System.out.println("Main thread interrupted.");
  34. }
  35. System.out.println("Main thread exiting.");
  36. }
  37. }
复制代码



7 个回复

倒序浏览
不错哦   加油加油
回复 使用道具 举报 1 0
怎么拿技术分啊
回复 使用道具 举报
不错哦   看了下分析的可以
回复 使用道具 举报
q953321 发表于 2015-7-16 16:47
不错哦   看了下分析的可以

谢谢。。。。。。。。
回复 使用道具 举报
线程优先级高,该线程优先调度。和时间片无关。
回复 使用道具 举报
我们十天后也要学习这
回复 使用道具 举报
阿彬 初级黑马 2015-7-16 17:52:09
8#
不错啊 ,挺好的
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马