歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Java中線程的使用

簡單的使用線程

1 . 擴展java.lang.Thread類

/**
*定義線程類
*/
public class MyThread extends Thread {  
  public void run() {  
   System.out.println("MyThread.run()");  
  }  
}  

//使用線程 MyThread myThread1 = new MyThread(); MyThread myThread2 = new MyThread(); myThread1.start(); myThread2.start();

2 . 實現java.lang.Runnable接口

/** 
* 實現Runnable接口的類
*/ 
publicclass DoSomethingimplements Runnable {
    private String name;

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

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

/** * 測試Runnable類實現的多線程程序 */ publicclass TestRunnable { publicstaticvoid 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(); } }

線程的同步與鎖

線程的同步是為了防止多個線程訪問一個數據對象時,對數據造成的破壞。
例如:兩個線程ThreadA、ThreadB都操作同一個對象Foo對象,並修改Foo對象上的數據。

public class Foo {
    privateint x = 100;

    publicint getX() {
        return x;
    } 

    publicint fix(int y) {
        x = x - y; 
        return x;
    } 
}
public class MyRunnable implements Runnable {
    private Foo foo =new Foo(); 

    public staticvoid main(String[] args) {
        MyRunnable r = new MyRunnable();
        Thread ta = new Thread(r,"Thread-A"); 
        Thread tb = new Thread(r,"Thread-B"); 
        ta.start(); 
        tb.start(); 
    } 

    public void run() {
        for (int i = 0; i < 3; i++) {
            this.fix(30);
            try {
                Thread.sleep(1); 
            } catch (InterruptedException e) {
                e.printStackTrace(); 
            } 
            System.out.println(Thread.currentThread().getName() + " :當前foo對象的x值= " + foo.getX());
        } 
    } 

    publicint fix(int y) {
        return foo.fix(y);
    } 
}

運行結果:

Thread-B :當前foo對象的x值= 40
Thread-A :當前foo對象的x值= 40
Thread-B :當前foo對象的x值= -20
Thread-A :當前foo對象的x值= -20
Thread-B :當前foo對象的x值= -80
Thread-A :當前foo對象的x值= -80

Copyright © Linux教程網 All Rights Reserved