『壹』 java程序設計,多線程,求大神給一份可運行的代碼
給你一個經典的例子。run裡面放空循環來觀察多線程是不合理的,空循環消耗時序極小,用sleep來間隔時間才是合理的。
{
privateThreadt;
privateStringthreadName;
RunnableDemo(Stringname){
threadName=name;
System.out.println("Creating"+threadName);
}
publicvoidrun(){
System.out.println("Running"+threadName);
try{
for(inti=4;i>0;i--){
System.out.println("Thread:"+threadName+","+i);
//Letthethreadsleepforawhile.
Thread.sleep(50);
}
}catch(InterruptedExceptione){
System.out.println("Thread"+threadName+"interrupted.");
}
System.out.println("Thread"+threadName+"exiting.");
}
publicvoidstart(){
System.out.println("Starting"+threadName);
if(t==null){
t=newThread(this,threadName);
t.start();
}
}
}
publicclassTestThread{
publicstaticvoidmain(Stringargs[]){
RunnableDemoR1=newRunnableDemo("Thread-1");
R1.start();
RunnableDemoR2=newRunnableDemo("Thread-2");
R2.start();
}
}
『貳』 java多線程詳細理解
多線程:指的是這個程序(一個進程)運行時產生了不止一個線程
並行與並發:
並行:多個cpu實例或者多台機器同時執行一段處理邏輯,是真正的同時。
並發:通過cpu調度演算法,讓用戶看上去同時執行,實際上從cpu操作層面不是真正的同時。並發往往在場景中有公用的資源,那麼針對這個公用的資源往往產生瓶頸,我們會用TPS或者QPS來反應這個系統的處理能力。
線程安全:經常用來描繪一段代碼。指在並發的情況之下,該代碼經過多線程使用,線程的調度順序不影響任何結果。這個時候使用多線程,我們只需要關注系統的內存,cpu是不是夠用即可。反過來,線程不安全就意味著線程的調度順序會影響最終結果,如不加事務的轉賬代碼:
同步:Java中的同步指的是通過人為的控制和調度,保證共享資源的多線程訪問成為線程安全,來保證結果的准確。如上面的代碼簡單加入@synchronized關鍵字。在保證結果准確的同時,提高性能,才是優秀的程序。線程安全的優先順序高於性能。
『叄』 什麼是Java多線程編程
一、 什麼是多線程:
我們現在所使用操作系統都是多任務操作系統(早期使用的DOS操作系統為單任務操作系統),多任務操作指在同一時刻可以同時做多件事(可以同時執行多個程序)。
多進程:每個程序都是一個進程,在操作系統中可以同時執行多個程序,多進程的目的是為了有效的使用CPU資源,每開一個進程系統要為該進程分配相關的系統資源(內存資源)
多線程:線程是進程內部比進程更小的執行單元(執行流|程序片段),每個線程完成一個任務,每個進程內部包含了多個線程每個線程做自己的事情,在進程中的所有線程共享該進程的資源;
主線程:在進程中至少存在一個主線程,其他子線程都由主線程開啟,主線程不一定在其他線程結束後結束,有可能在其他線程結束前結束。Java中的主線程是main線程,是Java的main函數;
二、 Java中實現多線程的方式:
繼承Thread類來實現多線程:
當我們自定義的類繼承Thread類後,該類就為一個線程類,該類為一個獨立的執行單元,線程代碼必須編寫在run()方法中,run方法是由Thread類定義,我們自己寫的線程類必須重寫run方法。
run方法中定義的代碼為線程代碼,但run方法不能直接調用,如果直接調用並沒有開啟新的線程而是將run方法交給調用的線程執行
要開啟新的線程需要調用Thread類的start()方法,該方法自動開啟一個新的線程並自動執行run方法中的內容
java多線程的啟動順序不一定是線程執行的順序,各個線程之間是搶佔CPU資源執行的,所有有可能出現與啟動順序不一致的情況。
CPU的調用策略:
如何使用CPU資源是由操作系統來決定的,但操作系統只能決定CPU的使用策略不能控制實際獲得CPU執行權的程序。
線程執行有兩種方式:
1.搶占式:
目前PC機中使用最多的一種方式,線程搶佔CPU的執行權,當一個線程搶到CPU的資源後並不是一直執行到此線程執行結束,而是執行一個時間片後讓出CPU資源,此時同其他線程再次搶佔CPU資源獲得執行權。
2.輪循式;
每個線程執行固定的時間片後讓出CPU資源,以此循環執行每個線程執行相同的時間片後讓出CPU資源交給下一個線程執行。
希望對您有所幫助!~
『肆』 如何用Java編寫多線程
在java中要想實現多線程,有兩種手段,一種是繼續Thread類,另外一種是實現Runable介面。
對於直接繼承Thread的類來說,代碼大致框架是:
?
123456789101112 class 類名 extends Thread{ 方法1; 方法2; … public void run(){ // other code… } 屬性1; 屬性2; … }
先看一個簡單的例子:
?
/** * @author Rollen-Holt 繼承Thread類,直接調用run方法 * */class hello extends Thread { public hello() { } public hello(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + "運行 " + i); } } public static void main(String[] args) { hello h1=new hello("A"); hello h2=new hello("B"); h1.run(); h2.run(); } private String name; }
【運行結果】:
A運行 0
A運行 1
A運行 2
A運行 3
A運行 4
B運行 0
B運行 1
B運行 2
B運行 3
B運行 4
我們會發現這些都是順序執行的,說明我們的調用方法不對,應該調用的是start()方法。
當我們把上面的主函數修改為如下所示的時候:
?
123456 public static void main(String[] args) { hello h1=new hello("A"); hello h2=new hello("B"); h1.start(); h2.start(); }
然後運行程序,輸出的可能的結果如下:
A運行 0
B運行 0
B運行 1
B運行 2
B運行 3
B運行 4
A運行 1
A運行 2
A運行 3
A運行 4
因為需要用到CPU的資源,所以每次的運行結果基本是都不一樣的,呵呵。
注意:雖然我們在這里調用的是start()方法,但是實際上調用的還是run()方法的主體。
那麼:為什麼我們不能直接調用run()方法呢?
我的理解是:線程的運行需要本地操作系統的支持。
如果你查看start的源代碼的時候,會發現:
?
1234567891011121314151617 public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus != 0 || this != me) throw new IllegalThreadStateException(); group.add(this); start0(); if (stopBeforeStart) { stop0(throwableFromStop); } } private native void start0();
注意我用紅色加粗的那一條語句,說明此處調用的是start0()。並且這個這個方法用了native關鍵字,次關鍵字表示調用本地操作系統的函數。因為多線程的實現需要本地操作系統的支持。
但是start方法重復調用的話,會出現java.lang.IllegalThreadStateException異常。
通過實現Runnable介面:
大致框架是:
?
123456789101112 class 類名 implements Runnable{ 方法1; 方法2; … public void run(){ // other code… } 屬性1; 屬性2; … }
來先看一個小例子吧:
?
2930 /** * @author Rollen-Holt 實現Runnable介面 * */class hello implements Runnable { public hello() { } public hello(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + "運行 " + i); } } public static void main(String[] args) { hello h1=new hello("線程A"); Thread demo= new Thread(h1); hello h2=new hello("線程B"); Thread demo1=new Thread(h2); demo.start(); demo1.start(); } private String name; }
【可能的運行結果】:
線程A運行 0
線程B運行 0
線程B運行 1
線程B運行 2
線程B運行 3
線程B運行 4
線程A運行 1
線程A運行 2
線程A運行 3
線程A運行 4
關於選擇繼承Thread還是實現Runnable介面?
其實Thread也是實現Runnable介面的:
?
12345678 class Thread implements Runnable { //… public void run() { if (target != null) { target.run(); } } }
其實Thread中的run方法調用的是Runnable介面的run方法。不知道大家發現沒有,Thread和Runnable都實現了run方法,這種操作模式其實就是代理模式。關於代理模式,我曾經寫過一個小例子呵呵,大家有興趣的話可以看一下:http://www.cnblogs.com/rollenholt/archive/2011/08/18/2144847.html
Thread和Runnable的區別:
如果一個類繼承Thread,則不適合資源共享。但是如果實現了Runable介面的話,則很容易的實現資源共享。
?
/** * @author Rollen-Holt 繼承Thread類,不能資源共享 * */class hello extends Thread { public void run() { for (int i = 0; i < 7; i++) { if (count > 0) { System.out.println("count= " + count--); } } } public static void main(String[] args) { hello h1 = new hello(); hello h2 = new hello(); hello h3 = new hello(); h1.start(); h2.start(); h3.start(); } private int count = 5; }
【運行結果】:
count= 5
count= 4
count= 3
count= 2
count= 1
count= 5
count= 4
count= 3
count= 2
count= 1
count= 5
count= 4
count= 3
count= 2
count= 1
大家可以想像,如果這個是一個買票系統的話,如果count表示的是車票的數量的話,說明並沒有實現資源的共享。
我們換為Runnable介面:
?
12345678910111213141516171819 /** * @author Rollen-Holt 繼承Thread類,不能資源共享 * */class hello implements Runnable { public void run() { for (int i = 0; i < 7; i++) { if (count > 0) { System.out.println("count= " + count--); } } } public static void main(String[] args) { hello he=new hello(); new Thread(he).start(); } private int count = 5; }
【運行結果】:
count= 5
count= 4
count= 3
count= 2
count= 1
總結一下吧:
實現Runnable介面比繼承Thread類所具有的優勢:
1):適合多個相同的程序代碼的線程去處理同一個資源
2):可以避免java中的單繼承的限制
3):增加程序的健壯性,代碼可以被多個線程共享,代碼和數據獨立。
所以,本人建議大家勁量實現介面。
?
『伍』 java多線程編程代碼如下,輸出結果如下:
首先,你同步的是具體的某個Test實例, 對於那個實例來說,實際上只有一個線程訪問了那個代碼塊,但是sum和other卻是多個線程同時去進行訪問,實際上這是不安全的,如果你想實現每次都輸出10000的效果,那麼正確的應該是在Test.class上加鎖,而不是獲取Test實例的鎖,修改後的代碼如下:
publicclassTestextendsThread{
publicstaticintsum=10000;
publicstaticintother=0;
publicvoidgetMoney(){
synchronized(Test.class){
System.out.println(Thread.currentThread().getName()+"開始執行");
sum=sum-100;
System.out.println("sum-100");
other=other+100;
System.out.println("other+100");
System.out.println(sum+other);
System.out.println(Thread.currentThread().getName()+"執行完成");
}
}
publicvoidrun(){
getMoney();
}
publicstaticvoidmain(String[]agrs){
Threadt[]=newThread[10];
for(inti=0;i<=9;i++){
t[i]=newTest();
t[i].start();
}
}
}
// 上面代碼能得到你的結果
『陸』 java線程的經典代碼
package threadgroup;
class ThreadDemo3 extends Thread {
private String name;
private int delay;
public ThreadDemo3(String sname, int i_delay) {
name = sname;
delay = i_delay;
}
public void run() {
try {
sleep(delay);
} catch (InterruptedException e) {
}
System.out.println("多線程測試!\n" + name + "\n" + delay);
}
}
public class testMyThread {
public static void main(String[] args) {
ThreadDemo3 th1,th2,th3;
th1 = new ThreadDemo3("線程1", (int) (Math.random() * 900));
th2 = new ThreadDemo3("線程2", (int) (Math.random() * 900));
th3 = new ThreadDemo3("線程3", (int) (Math.random() * 900));
th1.start();
th2.start();
th3.start();
}
}
package threadgroup;
public class threadDemo {
public static void main(String[] args) {
Thread t = Thread.currentThread();
t.setName("你好嗎?");
System.out.println("正在進行的Thread是:" + t);
try {
for (int i = 0; i < 5; i++) {
System.out.println("我不叫穆繼超" + i);
Thread.sleep(3000);
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("Thread has wrong" + e.getMessage());
}
}
}
package threadgroup;
public class threadDemo2 implements Runnable {
public threadDemo2() {
Thread t1 = Thread.currentThread();
t1.setName("第一個主進程");
System.out.println("正在運行" + t1);
Thread t2 = new Thread(this, "");
System.out.println("在創建一個進程");
t2.start();
try {
System.out.println("使他進入第一個睡眠狀態");
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Thread has wrong" + e.getMessage());
}
System.out.println("退出第一個進程");
}
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("進程" + i);
Thread.sleep(3000);
}
} catch (InterruptedException e) {
// TODO: handle exception
System.out.println("Thread has wrong" + e.getMessage());
}
System.out.println("退出第二個進程");
}
public static void main(String[] args) {
new threadDemo2();
}
}
『柒』 java多線程有幾種實現方法
繼承Thread類來實現多線程:
當我們自定義的類繼承Thread類後,該類就為一個線程類,該類為一個獨立的執行單元,線程代碼必須編寫在run()方法中,run方法是由Thread類定義,我們自己寫的線程類必須重寫run方法。
run方法中定義的代碼為線程代碼,但run方法不能直接調用,如果直接調用並沒有開啟新的線程而是將run方法交給調用的線程執行
要開啟新的線程需要調用Thread類的start()方法,該方法自動開啟一個新的線程並自動執行run方法中的內容
*java多線程的啟動順序不一定是線程執行的順序,各個線程之間是搶佔CPU資源執行的,所有有可能出現與啟動順序不一致的情況。
CPU的調用策略:
如何使用CPU資源是由操作系統來決定的,但操作系統只能決定CPU的使用策略不能控制實際獲得CPU執行權的程序。
線程執行有兩種方式:
1.搶占式:
目前PC機中使用最多的一種方式,線程搶佔CPU的執行權,當一個線程搶到CPU的資源後並不是一直執行到此線程執行結束,而是執行一個時間片後讓出CPU資源,此時同其他線程再次搶佔CPU資源獲得執行權。
2.輪循式;
每個線程執行固定的時間片後讓出CPU資源,以此循環執行每個線程執行相同的時間片後讓出CPU資源交給下一個線程執行。
『捌』 一個簡單java多線程的示例
for(int i=0;i<10;i++){
System.out.println(name+"運行,i="+i);
Thread.sleep(1)
}
for循環這樣改就行了,因為輸出10個數比較小,當你啟動啟動第二個線程時第一個線程已經運行完畢,所以兩次輸出都是順序輸出,要麼將i設置很大很大,要麼讓每次列印暫停一下
『玖』 求一個JAVA多線程例子,最好有代碼,謝謝啦!
package a.b.test;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Calculate1000 implements Callable<Integer>{
public Calculate1000(){}
public Calculate1000(int a, int b){
this.a = a;
this.b = b;
}
int a;
int b;
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//同步
Calculate1000 ca1 = new Calculate1000();
Date ds1 = new Date();
int result = 0;
for(int i = 1 ; i <= 1000 ; i++){
result = ca1.add(i, result);
}
System.out.println(result);
System.out.println("同步用時" + (new Date().getTime() - ds1.getTime()) + "MS");
//非同步
Date ds2 = new Date();
result = 0;
ExecutorService es = Executors.newFixedThreadPool(2);
Future<Integer> future1 = es.submit(new Calculate1000(1,500));
Future<Integer> future2 = es.submit(new Calculate1000(501,1000));
result = future1.get() + future2.get();
System.out.println(result);
System.out.println("非同步用時" + (new Date().getTime() - ds2.getTime()) + "MS");
es.shutdown();
}
private int add(int a, int b) throws Exception{
Thread.sleep(10);
return a + b;
}
@Override
public Integer call() throws Exception {
int res = 0;
for(int i = a ; i <= b ; i++){
res = this.add(res, i);
}
return res;
}
}
樓主你試一下這段代碼行不行,行的話請採納!