computer 版 (精华区)
发信人: arbo (arbo), 信区: program
标 题: java笔记7
发信站: 听涛站 (2001年09月17日10:49:49 星期一), 站内信件
发信人: airforce1 (五湖废人), 信区: Java
标 题: java笔记7
发信站: BBS 水木清华站 (Sun Apr 2 13:47:10 2000)
下午讲线程
同一个进程中的线程是共享内存和代码段的
建立线程的第一种方法
建立一个线程,要建立一个runable的借口
class mythread implements runnalble{
public void run(){ //每次启动线程的时候会调用
...
}
how to run
mythread a=new mythread();
Thread b=new Thread(a);
thread c=new Thread(a);
b.start(); // start the thread, 进入runnable状态,开始schedule
//同一时间只能有一个线程在run,其他的会排队
example:
public class t {
public static void main(String args[]) {
xx a=new xx();
yy b=new yy();
Thread t1=new Thread(a);
Thread t2=new Thread(b);
Thread t3=new Thread(b);
t1.start();
t2.start();
t3.start();
while(true)
System.out.println("aa");
}
}
class xx implements Runnable{
public void run(){
while (true)
System.out.println("bb");
}
}
class yy implements Runnable{
public void run(){
while (true)
System.out.println(Thread.currentThread().getName());
}
}
线程睡眠的实现。让出cpu时间
一个例子
注意里面已经设置了优先级了
// output aa aa aa bb aaa aa bb
// a has chance to run as t2 sleep
public class sleep {
public static void main(String args[]) {
xx a=new xx();
yy b=new yy();
Thread t1=new Thread(a);
Thread t2=new Thread(b);
t1.setPriority(1);
t1.start();
t2.start();
}
}
class xx implements Runnable{
public void run(){
while (true){
System.out.println("aa");
}
}
}
class yy implements Runnable{
public void run(){
while (true){
System.out.println("bb");
try{
Thread.sleep(10);
}catch(Exception e){}
}
}
}
优先级低的线程在其他线程sleep时,可以有执行机会
得到当前线程name, Thread.currentThread(), 返回引用。
线程等待,用join, 另外的线程join后,就等待那个线程结束
例子
// output aaa as main waiting for t1 finish
public class jointest {
public static void main(String args[]) {
xx a=new xx();
yy b=new yy();
Thread t1=new Thread(a);
Thread t2=new Thread(b);
t1.start();
try{
t1.join();
}
catch(Exception e){}
t2.start();
}
}
class xx implements Runnable{
public void run(){
while (true)
System.out.println("aa");
}
}
class yy implements Runnable{
public void run(){
while (true)
System.out.println("bb");
}
}
这里t2一直不会有机会得到执行权,因为t1是死循环。
--
--
※ 来源:·听涛站 tingtao.dhs.org·[FROM: 匿名天使的家]
Powered by KBS BBS 2.0 (http://dev.kcn.cn)
页面执行时间:1.060毫秒