多线程
来源:互联网 发布:syslog tcp默认端口 编辑:程序博客网 时间:2024/06/07 19:35
<李兴华视频笔记-2012-02-27>
一、进程与线程
进程消失,线程肯定消失;线程消失,进程不一定消失
二、Java的多线程实现
1.Thread类
java.lang包会在程序运行时自动导入
2.启动线程
必须使用Thread类中的start()方法
class MyThread extends Thread
{
private String name ;
public MyThread(String name){
this.name = name ;
}
public void run(){
for(int i=0;i<10;i++){
System.out.println(name + "运行,i=" +i);
}
}
}
public class ThreadDemo01
{
public static void main(String args[]){
MyThread mt1 = new MyThread("线程A") ;
MyThread mt2 = new MyThread("线程B") ;
mt1.start();
mt2.start();
}
}
程序运行效果:
(哪个线程先抢到CPU资源,哪个线程直接执行)
3.Thread().start()方法
public synchronized void start() {
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class MyThread extends Thread
{
private String name ;
public MyThread(String name){
this.name = name ;
}
public void run(){
for(int i=0;i<10;i++){
System.out.println(name + "运行,i=" +i);
}
}
}
public class ThreadDemo01
{
public static void main(String args[]){
MyThread mt1 = new MyThread("线程A") ;
MyThread mt2 = new MyThread("线程B") ;
mt1.start();
mt1.start();
}
}
三.Runnable接口
Runnable中只有run()方法
Thread(Runnable target)
分配新的 Thread
对象。
class MyThread implements Runnable
{
private String name ;
public MyThread(String name){
this.name = name ;
}
public void run(){
for(int i=0;i<10;i++){
System.out.println(name + "运行,i=" +i);
}
}
}
public class ThreadDemo01
{
public static void main(String args[]){
MyThread mt1 = new MyThread("线程A") ;
MyThread mt2 = new MyThread("线程B") ;
Thread t1 = new Thread(mt1) ;
Thread t2 = new Thread(mt2) ;
t1.start() ;
t2.start() ;
}
}
1.Thread类和Runnable接口
Thread类implementRunnable
使用Thread类操作多线程时,无法实现资源的共享;使用Runnable接口,能够实现资源的共享
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- django rest framework关联关系——Serializer relations
- 小笨霖英语笔记与老友记(1)
- 对hash table的两种理解
- 从零开始构建HTML 5 Web页面
- linux搭建vpn服务
- 多线程
- SqlServer2005和SqlServer2000的一点区别总结
- 自学XNA路(一)新手上路
- struts2和servlet区别
- 二进制 十进制快速转换方法
- struts2和hibernate整合步骤————转载
- perl初学
- Maven Jetty Plugin运行配置jetty:run
- Ubuntu下安装、配置MySQL与使用实践