導航:首頁 > 編程語言 > java多線程代碼

java多線程代碼

發布時間:2022-12-10 23:14:50

『壹』 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多線程詳細理解

『叄』 什麼是Java多線程編程

一、 什麼是多線程:

我們現在所使用操作系統都是多任務操作系統(早期使用的DOS操作系統為單任務操作系統),多任務操作指在同一時刻可以同時做多件事(可以同時執行多個程序)。

『肆』 如何用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多線程有幾種實現方法

『捌』 一個簡單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;
}
}
樓主你試一下這段代碼行不行,行的話請採納!

閱讀全文

與java多線程代碼相關的資料

熱點內容
怎麼查找雲伺服器上的ftp 瀏覽:154
我的世界伺服器如何注冊賬號 瀏覽:932
統計英文字元python 瀏覽:423
linux信息安全 瀏覽:908
壓縮機接線柱爆 瀏覽:999
程序員自主創業 瀏覽:584
匯編程序員待遇 瀏覽:359
怎麼批量有順序的命名文件夾 瀏覽:211
杭州程序員健身 瀏覽:19
dvd光碟存儲漢子演算法 瀏覽:758
蘋果郵件無法連接伺服器地址 瀏覽:963
phpffmpeg轉碼 瀏覽:672
長沙好玩的解壓項目 瀏覽:145
專屬學情分析報告是什麼app 瀏覽:564
php工程部署 瀏覽:833
android全屏透明 瀏覽:737
阿里雲伺服器已開通怎麼辦 瀏覽:803
光遇為什麼登錄時伺服器已滿 瀏覽:302
PDF分析 瀏覽:486
h3c光纖全工半全工設置命令 瀏覽:143