c++程序!
来源:互联网 发布:网络歌曲dj大连唱视频 编辑:程序博客网 时间:2024/05/01 04:48
进程指运行中的程序,每个进程都会分配一个内存空间,一个进程中存在多个线程,启动一个JAVA虚拟机,就是打开个一个进程,一个进程有多个线程,当多个线程同时进行,就叫并发。
J ava创建线程的两种方式为: 继承Thread类 和实现Runnable接口
Thread类
1、通过覆盖run方法实现线程要执行的程序代码
2、Start()开始执行多线程
package com.bin.duoxiancheng;
public class d1 extends Thread{
public void run(){
for(int i=0 ; i<50; i++){
System.out.println(i);
System.out.println(currentThread()。getName());
try {
sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
new d1()。start();
new d1()。start();
}
}
多个线程共享一个实例的时候,代码代码如下:
package com.bin.duoxiancheng;
public class d1 extends Thread{
int i=0;
public void run(){
for(i=0 ; i<50; i++){
System.out.println(i);
System.out.println(currentThread()。getName());
try {
sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
new d1()。start();
new d1()。start();
}
}
结果如下所示:
0
Thread-1
0
Thread-0
1
Thread-1
1
实际2个线程在操纵不同的变量a,在执行run方法时候,线程把a都当做自己的变量在执行。
Runnable接口实现多线程
当一个继承自Thread时,就不能再继承其他类,使用Runnable接口解决了此问题,在新建一个Thread类中,在构造方法中初始化
Thread(Runnable target)
分配新的 Thread 对象。
Thread(Runnable target,String name)
分配新的 Thread 对象。
package com.bin.duoxiancheng;
public class D2 implements Runnable{
int i=0;
public void run(){
for(i=0 ; i<50; i++){
System.out.println(i);
System.out.println(Thread.currentThread()。getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
D2 d=new D2();
Thread t=new Thread(d);
t.start();
}
}
- C程序
- c 程序
- C程序
- C程序
- c程序。
- c程序
- c 程序
- c程序
- C程序
- C程序
- c程序
- c程序
- c程序
- c程序
- C程序
- c程序
- c程序
- c程序
- C#中JSON数组填充给Combox控件
- 叶君—国画大师笔下的“忠义千秋”
- mysql必知必会 第十三章 分组数据
- The Struts dispatcher cannot be found在struts2中出现的问题
- 叶君.画梅大师
- c++程序!
- C++ using namespace std 详解
- mysql5.5.28.tar.gz编译安装操作笔记
- Linux学习笔记(一)
- 三种继承
- Python网络爬虫4 ---- Linux下编写最简单的scrapy网络爬虫项目
- c++的一些 细节!
- Python中字符编码的总结和对比:Python 2.x的str和unicode vs Python 3.x的bytes和str
- 简明 Vim 练级攻略