Java线程,让人爱恨交加。下面通过迅雷公司的笔试题,来谈谈Java线程
一、线程的五种状态
使用Java能方便的写出多线程代码,如果在使用前能了解线程运行时的各种状态,对于理解线程编程会有很大助益
下面从一个示意图来了解一下线程状态:
当一个线程被创建后,调用它的start()方法,使其进入可运行状态,也就说调用完start方法后线程并不会立即运行,而是处于就绪状态。一旦进入运行状态,就会有三种结果:
1、线程执行完毕(死亡)
2、线程由于各种原因,比如说睡眠、运行超时、更高优先级的线程进入、IO等待或join等等,这个时候则暂停运行。
3、在线程运行过程中,调用了某一对象的wait方法,直到其它线程调用此对象的notify或notifyAll 方法,使当前线程恢复可运行状态。可 运行状态指的是java的线程调度器已经通知了操作系统,将这个线程安排到就绪队列,等待CPU执行。
二、线程的概念
通俗的理解:线程不是一行代码,也不是一个方法,它是一个执行序列。所有代码都在这个序列当中一步步执行至到结束。
三、在java中创建线程有两种方法
1、继承Thread 重写run方法
2、实现Runnable接口 实现其中的run 方法
前面三点了解一下先,接下来看迅雷公司的这道笔试题:
有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC…
第一种方法如下:
ta.setThread(tb);
tb.setThread(tc);
tc.setThread(td);
td.setThread(ta);
ta.setName("A");
tb.setName("B");
tc.setName("C");
td.setName("D");
ta.start();
tb.start();
tc.start();
td.start();
}
}
class Thread_A extends Thread {
Thread t;
public void setThread(Thread t) {
this.t = t;
}
public void run() {
int i = 0;
while(i++ < 10) {
System.out.print(Thread.currentThread().getName());
t.interrupt();
try {
this.join();
} catch (InterruptedException e) {
}
}
}
}
class Thread_E extends Thread {
Thread t;
public void setThread(Thread t) {
this.t = t;
}
public void run() {
int i = 0;
while(i++ < 10) {
try {
this.join();
} catch (InterruptedException e) {
}
System.out.print(Thread.currentThread().getName());
t.interrupt();
}
}
}
第二种方法如下:
/* 限制此类只创建一个对象 */
private static MajusculeABC maObj =null;
private MajusculeABC() {}
public static MajusculeABC newInstance(){
if(maObj == null) {
maObj = new MajusculeABC();
}
return maObj;
}
public void setCharactor() {
this.charactor += 1;
if(this.charactor == 'D') {
this.charactor = 'A';
}
}
public char getCharactor() {
return this.charactor;
}
}
class Thread_ABC implements Runnable {
private MajusculeABC maj;
private char charactor = ' ';
public Thread_ABC(MajusculeABC maj, char charactor) {
this.maj = maj;
this.charactor = charactor;
}
public void run() {
int i = 0;
while (i<10) {
synchronized (maj) {
while(this.charactor != maj.getCharactor()) {
try {
maj.wait();
} catch (InterruptedException e) {}
}
System.out.print(this.charactor);
i++;
maj.setCharactor();
maj.notifyAll();
}
}
}
}
以上两种方法都未写注释,第一种方法使用线程中的join() 达到目的,第二种方法就是同步对象
对于线程的各种状态、线程间的通信、线程组、线程池等等,下回分解