进程心得
进程:
线程可以有两种实现方式:
一种是继承Thread类;另一种是实现Runable接口。
实现资源共享的时候一般利用实现Runnable接口的方式;
实现Runnable接口比继承Thread类所具有的优势:
1):适合多个相同的程序代码的线程去处理同一个资源
2):可以避免java中的单继承的限制
3):增加程序的健壮性,代码可以被多个线程共享,代码和数据独立。
接下来看一个后台线程的例子:
eg:
public class Test implements Runnable{
public void run(){
for( int i=0;i<10;i++){
System.out.println("后台线程启动第"+i+“次”);
}
}
public
static
void
main(String[] args) {
Test t
=
new
Test
();
Thread demo =
new
Thread(t,
"线程名字"
);
demo.setDaemon(
true
);
demo.start();
}
}
如果有多个线程的话:
可以设立一个主线程,设立多个后台线程
甚至可以在主线程的RUN()的实现中调用后台线程
还有可以设定线程的优先级 setPriority(8);
查看当前线程的名字:Thread.currentThread().getName()+
"运行"
+i
买票系统的线程:
class
hello
implements
Runnable {
public
void
run() {
for
(
int
i=
0
;i<
10
;++i){
synchronized
(
this
) {
if
(count>
0
){
try
{
Thread.sleep(
1000
);
}
catch
(InterruptedException e){
e.printStackTrace();
}
System.out.println(count--);
}
}
}
}
public
static
void
main(String[] args) {
hello he=
new
hello();
Thread h1=
new
Thread(he);
Thread h2=
new
Thread(he);
Thread h3=
new
Thread(he);
h1.start();
h2.start();
h3.start();
}
private
int
count=
5
;
}
|
【运行结果】:(每一秒输出一个结果)
5
4
3
2
1