黑马程序员技术交流社区
标题:
Java 多线程编程
[打印本页]
作者:
pi408637535
时间:
2015-7-15 19:03
标题:
Java 多线程编程
Java 线程很简单就三种状态:就绪,运行,空闲 (进程是分配资源的基本单位,线程在进程中运行)
Java要运行线程,这个类要么是继承Thread,要么Runnable。(我们一般选择接口,因为Java是单继承模式)
Java的线程是有优先级的。//高级 分的时间片多 反之亦然
两个实例
Thread继承:
// 通过继承 Thread 创建线程
class NewThread extends Thread {
NewThread() {
// 创建第二个新线程
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // 开始线程
}
// 第二个线程入口
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// 让线程休眠一会
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ExtendThread {
public static void main(String args[]) {
new NewThread(); // 创建一个新线程
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
复制代码
Runnable 接口:
// 创建一个新的线程
class NewThread implements Runnable {
Thread t;
NewThread() {
// 创建第二个新线程
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // 开始线程
}
// 第二个线程入口
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// 暂停线程
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // 创建一个新线程
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
复制代码
作者:
小虎199406
时间:
2015-7-15 19:07
不错哦 加油加油
作者:
pi408637535
时间:
2015-7-15 19:09
怎么拿技术分啊
作者:
q953321
时间:
2015-7-16 16:47
不错哦 看了下分析的可以
作者:
pi408637535
时间:
2015-7-16 16:50
q953321 发表于 2015-7-16 16:47
不错哦 看了下分析的可以
谢谢。。。。。。。。
作者:
新手ing
时间:
2015-7-16 17:46
线程优先级高,该线程优先调度。和时间片无关。
作者:
鲁枝权双元
时间:
2015-7-16 17:47
我们十天后也要学习这
作者:
阿彬
时间:
2015-7-16 17:52
不错啊 ,挺好的
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2