您的位置:首页 > 编程语言 > Java开发

java之线程

2015-11-11 17:37 323 查看
多进程:在操作系统中能(同时)运行多个任务(程序)

多线程:在同一应用程序中有多个顺序流(同时)执行

方法一:
//创建Thread子类
class FirstThread extends Thread{
//重写run函数
public void run(){
for(int  i = 0; i < 5;i++){
System.out.println("FirstThread---->"+i);
}
}
}

class Test{
public static void main(String args[]){
FirstThread ft = new FirstThread();
ft.start();//启动线程

for(int  i = 0; i < 5;i++){
System.out.println("main---->"+i);
}
}
}

执行结果:
main---->0
FirstThread---->0
main---->1
FirstThread---->1
main---->2
FirstThread---->2
main---->3
main---->4
FirstThread---->3
FirstThread---->4
结果分析:程序主要启动main和FirstThread线程两个线程,线程之间的切换是不定时的,因为它们占用CPU的时机不一样,如果再次编译运行程序,则会执行不一样的结果。


方法二:(常用)
class RunnableImpl implements Runnable{
public void run(){
for(int i = 0;i < 5;i++){
System.out.println("main--->"+ i);
}
}
}

class Test{
public static void main(String args[]){
RunnableImpl ri = new RunnableImpl();
Thread t = new Thread(ri);
t.start();
}
}
线程的简单控制方法:
中断线程:
1. Thread.sleep()   //让线程休眠一段时间(时间长短由参数决定),休眠后还要再跟别的线程抢CPU
2. Thread.yield()   //让线程主动让出cpu,让出后还要继续和其他线程抢CPU

设置线程的优先级(优先级的高表示占用CPU的概率比较大)
getPriority()   获取线程的优先级
setPriority()   设置线程的优先级


多线程的数据安全(数据的完整性)

同步线程的方法()

class MyThread implements Runnable{
int i = 100;
public void run(){
while(true){
synchronized(this){//使得线程的数据同步
System.out.println(Thread.currentThread().getName() + i);
i--;
Thread.yield();
if(i < 0){
break;
}
}
}
}
}

class Test{
public static void main(String args[]){

MyThread myThread = new MyThread();
Thread t1 = new Thread(myThread);
Thread t2 = new Thread(myThread);
t1.setName("线程1 ");
t2.setName("线程2 ");

t1.start();
t2.start();
}
}


synchronized深入理解

一个线程获得一个对象的同步锁,则这个对象的所有其他同步的代码都不能执行,都需要等待同步锁的代码释放时候

才能执行,但不属于同步锁的代码可以执行

class Service{
public void fun1(){
synchronized(this){
try{
Thread.sleep(3 * 1000);
}catch(Exception e){
System.out.println(e);
}
System.out.println("fun1");
}
}

public void fun2(){
synchronized(this){
System.out.println("fun2");
}
}
}

class MyThread1 implements Runnable{
private Service service;

public MyThread1(Service service){
this.service = service;
}
public void run(){
service.fun1();
}
}

class MyThread2 implements Runnable{
private Service service;

public MyThread2(Service service){
this.service = service;
}
public void run(){
service.fun2();
}
}

class Test{
public static void main(String args[]){
Service service = new Service();
Thread t1 = new Thread(new MyThread1(service));
Thread t2 = new Thread(new MyThread2(service));

t1.start();
t2.start();
}
}

结果输出:fun1()
fun2()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: