线程的创建
线程:利用CPU的资源,让一个程序“同时”运行多个功能;举例:
public class A{
public void s1(){
if (true)
System.out.println("大家好");
}
public void s2(){
if(true){
System.out.println("不会");
}
}
public static void main(String args[]){
s1();
s2();
}
}
/*
由此可见,运行main方法s1()时,永远不可能执行s2();方法,如果要让s1 s2都有机会运行,就要使用线程了
*/
1.Thread子类创建线程
class SpeakDog extends Thread{
public void run() {
for(int i=0;i<21;i++) {
System.out.print(i+"Dog"+" ");
}
}
}
class SpeakCat extends Thread{
public void run() {
for (int i=21;i<43;i++) {
System.out.print(i+"Cat"+" ");
}
}
}
public class Thead_t1 {
public static void main(String[] args) {
SpeakDog d = new SpeakDog();
d.start();
SpeakCat c = new SpeakCat();
c.start();
}
}
运行结果:
0Dog 1Dog 2Dog 3Dog 4Dog 5Dog 6Dog 7Dog 8Dog 9Dog 10Dog 11Dog 12Dog 13Dog 14Dog 15Dog 16Dog 17Dog 18Dog 21Cat 22Cat 23Cat 24Cat 25Cat 26Cat 19Dog 27Cat 28Cat 29Cat 30Cat 31Cat 20Dog 32Cat 33Cat 34Cat 35Cat 36Cat 37Cat 3
总结:
- 顺序不一 ,18Dog后就是21Cat 19Dog后就是27Cat了。由此看出两个线程都是有机会运行的;
- 创建线程可采用继承Thread类的方法,看源码发现Thread其实是继承了接口Runnable;
- 使用的是Thread子类创建的对象;但是由于继承具有单继承的特性,所以不太灵活;
Thread.java部分源码
public
class Thread implements Runnable {
/* Make sure registerNatives is the first thing <clinit> does. */
private static native void registerNatives();
static {
registerNatives();
}
private volatile String name;
private int priority;
private Thread threadQ;
private long eetop;
...
2.实现Runnable接口
public class Thread_t3 {
public static void main(String args[]){
Th t = new Th();
Thread th = new Thread(t);
Thread th2 = new Thread();
th.start();
th2.start();
}
}
class Th implements Runnable{
public void run(){
System.out.println("使用接口创建Thread类");
}
}
由上述代码可得:
- 第二种创建线程的方法:实现Runnable的接口;
- 一个类可以实现多个接口,具有灵活性;
- Thread a = new Thread(Runnable a);其中a是Runnable接口的实例,a被称为目标对象;
- 上述代码可以看出,目标对象和Thread的对象没有然后关联,二者是完全解耦的;
- 目标对象可被多个线程使用,如果目标对象中具有成员变量,那么该变量是可以实现共享的;
- 其实目标对象和线程之间可以有弱耦性:
public class Thread_t4{
public static void main(String args[]){
T t = new T();
t.t1.start();
t.t2.start();
}
}
class T implements Runnable{
int sum;
Thread t1,t2;
public void setSum(int sum){
this.sum = sum;
}
T(){
t1 = new Thread(this);
t2 = new Thread(this);
}
public void run(){
if (Thread.currentThread() == t1){
System.out.println("我是t1");
sum = sum-2;
}
else if (Thread.currentThread() == t2){
System.out.println("我是t2");
sum = sum-1;
}
System.out.println("剩下"+sum+"水");
try {
Thread.sleep(1000);
}catch(InterruptedException e){
if (sum<=0){
System.out.println("结束");
return;
}
}
}
}