Java多线程

来源:互联网 发布:淘宝网资金保护中 编辑:程序博客网 时间:2024/05/22 03:10

一、线程的状态:new新建、runnable可运行、blocked阻塞、running运行、dead结束,转换如下:



二、实现线程类

1、extends Thread类

public class TestThread extends Thread{ 
    public TestThread(String name) { 
        super(name); 
    } 

    public void run() { 
        for(int i = 0;i<5;i++){ 
            for(long k= 0; k <100000000;k++); 
        System.out.println(this.getName()+" :"+i); 
        } 
    } 

    public static void main(String[] args) { 
        Thread t1 = new TestThread("阿三"); 
        Thread t2 = new TestThread("李四"); 
        t1.start(); 
        t2.start(); 
    } 
}

2、implements runnable接口

public class DoSomething implements Runnable { 
    private String name; 

    public DoSomething(String name) { 
        this.name = name; 
    } 

    public void run() { 
        for (int i = 0; i < 5; i++) { 
            for (long k = 0; k < 100000000; k++) ; 
            System.out.println(name + ": " + i); 
        } 
    } 
}


public class TestRunnable { 
    public static void main(String[] args) { 
        DoSomething ds1 = new DoSomething("阿三"); 
        DoSomething ds2 = new DoSomething("李四"); 

        Thread t1 = new Thread(ds1); 
        Thread t2 = new Thread(ds2); 

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

三、线程同步

1、同步方法

public synchronized void save(){

......

}

   注: synchronized关键字也可以修饰静态方法,此时如果调用该静态方法,将会锁住整个类

2、同步代码块

synchronized(object){ 

......

    }


原创粉丝点击