導航:首頁 > 編程語言 > java模擬多線程

java模擬多線程

發布時間:2022-09-12 22:05:38

A. java多線程怎麼測試

測試並發的性能嗎?可以用Jmeter進行模擬多線程測試

B. java多線程有幾種實現方法,都是什麼同步有幾種實現方法,都是什麼

java中多線程的實現方法有兩種:1.直接繼承thread類;2.實現runnable介面;同步的實現方法有五種:1.同步方法;2.同步代碼塊;3.使用特殊域變數(volatile)實現線程同步;4.使用重入鎖實現線程同步;5.使用局部變數實現線程同步

其中多線程實現過程中需注意重寫或者覆蓋run()方法,而對於同步的實現方法中使用較常使用的是利用synchronized編寫同步方法和代碼塊。

C. java如何模擬一個多線程環境

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class FrameTest extends JFrame {
public FrameTest() {
super("Swing 例子");
this.setSize(300, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setLayout(new FlowLayout());
this.add(new CounterJButton());
this.add(new CounterJButton());
this.add(new CounterJButton());
this.setVisible(true);
}

static class CounterJButton extends JButton implements Runnable,
ActionListener {
private boolean started = false;
private int count = 0;

public CounterJButton() {
super("按我開始計數");
this.addActionListener(this);
}

public void run() {
while (started) {
this.setText("按我暫停 " + String.valueOf(count++));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}

public void actionPerformed(ActionEvent e) {
if (started) {
this.started = false;
this.setText("按我恢復計數 " + count);
} else {
this.started = true;
new Thread(this).start();
}
}
}

public static void main(String[] args) {
new FrameTest();
}
}

D. 什麼是Java多線程編程

一、 什麼是多線程:

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

E. 用java編寫多線程銀行ATM 模擬程序

先構建一個客戶端,再構建一個伺服器端,其實做一個簡單的界面,建立一個資料庫,調用SQl 語句,,實現單機,模擬多線程的就可以了,伺服器部分不做也可以模擬出來。。

PS:這不會是程序專題訓練一吧。。。

F. JAVA多線程 模擬每隔一秒輸入一個數據

在編寫Java程序時,有時候需要在Java程序中執行另外一個程序。
1、啟動程序Java提供了兩種方法用來啟動其它程序:

(1)使用Runtime的exec()方法

(2)使用ProcessBuilder的start()方法

不管在哪種操作系統下,程序具有基本類似的一些屬性。一個程序啟動後就程序操作系統的一個進程,進程在執行的時候有自己的環境變數、有自己的工作目錄。Runtime和ProcessBuilder提供了不同的方式來啟動程序,設置啟動參數、環境變數和工作目錄。

能夠在Java中執行的外部程序,必須是一個實際存在的可執行文件,對於shell下的內嵌命令是不能直接執行的。

採用Runtime的exec執行程序時,首先要使用Runtime的靜態方法得到一個Runtime,然後調用Runtime的exec方
法。可以將要執行的外部程序和啟動參數、環境變數、工作目錄作為參數傳遞給exec方法,該方法執行後返回一個Process代表所執行的程序。

Runtime有六個exec方法,其中兩個的定義為:

public Process exec(String[] cmdarray, String[] envp, File dir)

public Process exec(String command, String[] envp, File dir)

cmdarray和command為要執行的命令,可以將命令和參數作為一個字元串command傳遞給exec()方法,也可以將命令和參數一個一個的方在數組cmdarray里傳遞給exec()方法。

envp為環境變數,以name=value的形式放在數組中。dir為工作目錄。

可以不要dir參數,或者不要envp和dir參數,這樣就多出了其它4個exec()方法。如果沒有dir參數或者為null,那麼新啟動的
進程就繼承當前java進程的工作目錄。如果沒有envp參數或者為null,那麼新啟動的進程就繼承當前java進程的環境變數。

也可以使用ProcessBuilder類啟動一個新的程序,該類是後來添加到JDK中的,而且被推薦使用。通過構造函數設置要執行的命令以及
參數,或者也可以通過command()方法獲取命令信息後在進行設置。通過directory(File directory)
方法設置工作目錄,通過environment()獲取環境變數信息來修改環境變數。

在使用ProcessBuilder構造函數創建一個新實例,設置環境變數、工作目錄後,可以通過start()方法來啟動新程序,與Runtime的exec()方法一樣,該方法返回一個Process對象代表啟動的程序。

ProcessBuilder與Runtime.exec()方法的不同在於ProcessBuilder提供了
redirectErrorStream(boolean redirectErrorStream)
方法,該方法用來將進程的錯誤輸出重定向到標准輸出里。即可以將錯誤輸出都將與標准輸出合並。

2、Process

不管通過那種方法啟動進程後,都會返回一個Process類的實例代表啟動的進程,該實例可用來控制進程並獲得相關信息。Process 類提供了執行從進程輸入、執行輸出到進程、等待進程完成、檢查進程的退出狀態以及銷毀(殺掉)進程的方法:

(1) void destroy()

殺掉子進程。

一般情況下,該方法並不能殺掉已經啟動的進程,不用為好。

(2) int exitValue()

返回子進程的出口值。

只有啟動的進程執行完成、或者由於異常退出後,exitValue()方法才會有正常的返回值,否則拋出異常。

(3)InputStream getErrorStream()

獲取子進程的錯誤流。

如果錯誤輸出被重定向,則不能從該流中讀取錯誤輸出。

(4)InputStream getInputStream()

獲取子進程的輸入流。

可以從該流中讀取進程的標准輸出。

(5)OutputStream getOutputStream()

獲取子進程的輸出流。

寫入到該流中的數據作為進程的標准輸入。

(6) int waitFor()

導致當前線程等待,如有必要,一直要等到由該 Process 對象表示的進程已經終止。

通過該類提供的方法,可以實現與啟動的進程之間通信,達到交互的目的。

3、從標准輸出和錯誤輸出流讀取信息

從啟動其他程序的Java進程看,已啟動的其他程序輸出就是一個普通的輸入流,可以通過getInputStream()和getErrorStream來獲取。

對於一般輸出文本的進程來說,可以將InputStream封裝成BufferedReader,然後就可以一行一行的對進程的標准輸出進行處理。

4、舉例

(1)Runtime.exec()

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
public class Test1 {
public static void main(String[] args) {
try {
Process p = null;
String line = null;
BufferedReader stdout = null;

//list the files and directorys under C:\
p = Runtime.getRuntime().exec("CMD.exe /C dir", null, new File("C:\\"));
stdout = new BufferedReader(new InputStreamReader(p
.getInputStream()));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
stdout.close();

//echo the value of NAME
p = Runtime.getRuntime().exec("CMD.exe /C echo %NAME%", new String[] {"NAME=TEST"});
stdout = new BufferedReader(new InputStreamReader(p
.getInputStream()));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
stdout.close();
} catch (Exception e) {
e.printStackTrace();
}
}

(2)ProcessBuilder

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
try {
List list = new ArrayList();
ProcessBuilder pb = null;
Process p = null;
String line = null;
BufferedReader stdout = null;

//list the files and directorys under C:\
list.add("CMD.EXE");
list.add("/C");
list.add("dir");
pb = new ProcessBuilder(list);
pb.directory(new File("C:\\"));
p = pb.start();

stdout = new BufferedReader(new InputStreamReader(p
.getInputStream()));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
stdout.close();
//echo the value of NAME
pb = new ProcessBuilder();
mand(new String[] {"CMD.exe", "/C", "echo %NAME%"});
pb.environment().put("NAME", "TEST");
p = pb.start();

stdout = new BufferedReader(new InputStreamReader(p
.getInputStream()));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
stdout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

5、獲取進程的返回值

通常,一個程序/進程在執行結束後會向操作系統返回一個整數值,0一般代表執行成功,非0表示執行出現問題。有兩種方式可以用來獲取進程的返回
值。一是利用waitFor(),該方法是阻塞的,執導進程執行完成後再返回。該方法返回一個代表進程返回值的整數值。另一個方法是調用
exitValue()方法,該方法是非阻塞的,調用立即返回。但是如果進程沒有執行完成,則拋出異常。

6、阻塞的問題

由Process代表的進程在某些平台上有時候並不能很好的工作,特別是在對代表進程的標准輸入流、輸出流和錯誤輸出進行操作時,如果使用不慎,有可能導致進程阻塞,甚至死鎖。

如果將以上事例中的從標准輸出重讀取信息的語句修改為從錯誤輸出流中讀取:

stdout = new BufferedReader(new InputStreamReader(p
.getErrorStream()));

那麼程序將發生阻塞,不能執行完成,而是hang在那裡。

當進程啟動後,就會打開標准輸出流和錯誤輸出流准備輸出,當進程結束時,就會關閉他們。在以上例子中,錯誤輸出流沒有數據要輸出,標准輸出流中
有數據輸出。由於標准輸出流中的數據沒有被讀取,進程就不會結束,錯誤輸出流也就不會被關閉,因此在調用readLine()方法時,整個程序就會被阻
塞。為了解決這個問題,可以根據輸出的實際先後,先讀取標准輸出流,然後讀取錯誤輸出流。

但是,很多時候不能很明確的知道輸出的先後,特別是要操作標准輸入的時候,情況就會更為復雜。這時候可以採用線程來對標准輸出、錯誤輸出和標准輸入進行分別處理,根據他們之間在業務邏輯上的關系決定讀取那個流或者寫入數據。

針對標准輸出流和錯誤輸出流所造成的問題,可以使用ProcessBuilder的redirectErrorStream()方法將他們合二為一,這時候只要讀取標准輸出的數據就可以了。

當在程序中使用Process的waitFor()方法時,特別是在讀取之前調用waitFor()方法時,也有可能造成阻塞。可以用線程的方法來解決這個問題,也可以在讀取數據後,調用waitFor()方法等待程序結束。

總之,解決阻塞的方法應該有兩種:

(1)使用ProcessBuilder類,利用redirectErrorStream方法將標准輸出流和錯誤輸出流合二為一,在用start()方法啟動進程後,先從標准輸出中讀取數據,然後調用waitFor()方法等待進程結束。

如:

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Test3 {
public static void main(String[] args) {
try {
List list = new ArrayList();
ProcessBuilder pb = null;
Process p = null;
String line = null;
BufferedReader stdout = null;

//list the files and directorys under C:\
list.add("CMD.EXE");
list.add("/C");
list.add("dir");
pb = new ProcessBuilder(list);
pb.directory(new File("C:\\"));
//merge the error output with the standard output
pb.redirectErrorStream(true);
p = pb.start();

//read the standard output
stdout = new BufferedReader(new InputStreamReader(p
.getInputStream()));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
int ret = p.waitFor();
System.out.println("the return code is " + ret);

stdout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

(2)使用線程

import java.util.*;
import java.io.*;
class StreamWatch extends Thread {
InputStream is;
String type;
List output = new ArrayList();
boolean debug = false;
StreamWatch(InputStream is, String type) {
this(is, type, false);
}
StreamWatch(InputStream is, String type, boolean debug) {
this.is = is;
this.type = type;
this.debug = debug;
}
public void run() {
try {
PrintWriter pw = null;
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
output.add(line);
if (debug)
System.out.println(type + ">" + line);
}
if (pw != null)
pw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public List getOutput() {
return output;
}
}
public class Test5 {
public static void main(String args[]) {
try {
List list = new ArrayList();
ProcessBuilder pb = null;
Process p = null;
// list the files and directorys under C:\
list.add("CMD.EXE");
list.add("/C");
list.add("dir");
pb = new ProcessBuilder(list);
pb.directory(new File("C:\\"));
p = pb.start();
// process error and output message
StreamWatch errorWatch = new StreamWatch(p.getErrorStream(),
"ERROR");
StreamWatch outputWatch = new StreamWatch(p.getInputStream(),
"OUTPUT");
// start to watch
errorWatch.start();
outputWatch.start();
//wait for exit
int exitVal = p.waitFor();
//print the content from ERROR and OUTPUT
System.out.println("ERROR: " + errorWatch.getOutput());
System.out.println("OUTPUT: " + outputWatch.getOutput());

System.out.println("the return code is " + exitVal);
} catch (Throwable t) {
t.printStackTrace();
}
}
}

7、在Java中執行Java程序

執行一個Java程序的關鍵在於:

(1)知道JAVA虛擬機的位置,即java.exe或者java的路徑

(2)知道要執行的java程序的位置

(3)知道該程序所依賴的其他類的位置

舉一個例子,一目瞭然。

(1)待執行的Java類

public class MyTest {
public static void main(String[] args) {
System.out.println("OUTPUT one");
System.out.println("OUTPUT two");
System.err.println("ERROR 1");
System.err.println("ERROR 2");
for(int i = 0; i < args.length; i++)
{
System.out.printf("args[%d] = %s.", i, args[i]);
}
}
}
(2)執行該類的程序

import java.util.*;
import java.io.*;
class StreamWatch extends Thread {
InputStream is;

String type;

List output = new ArrayList();

boolean debug = false;

StreamWatch(InputStream is, String type) {
this(is, type, false);
}

StreamWatch(InputStream is, String type, boolean debug) {
this.is = is;
this.type = type;
this.debug = debug;
}

public void run() {
try {
PrintWriter pw = null;

InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
output.add(line);
if (debug)
System.out.println(type + ">" + line);
}
if (pw != null)
pw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

public List getOutput() {
return output;
}
}

public class Test6 {
public static void main(String args[]) {
try {
List list = new ArrayList();
ProcessBuilder pb = null;
Process p = null;

String java = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
// list the files and directorys under C:\
list.add(java);
list.add("-classpath");
list.add(classpath);
list.add(MyTest.class.getName());
list.add("hello");
list.add("world");
list.add("good better best");

pb = new ProcessBuilder(list);
p = pb.start();

System.out.println(mand());

// process error and output message
StreamWatch errorWatch = new StreamWatch(p.getErrorStream(),
"ERROR");
StreamWatch outputWatch = new StreamWatch(p.getInputStream(),
"OUTPUT");

// start to watch
errorWatch.start();
outputWatch.start();

//wait for exit
int exitVal = p.waitFor();

//print the content from ERROR and OUTPUT
System.out.println("ERROR: " + errorWatch.getOutput());
System.out.println("OUTPUT: " + outputWatch.getOutput());

System.out.println("the return code is " + exitVal);

} catch (Throwable t) {
t.printStackTrace();
}
}
}

G. java模擬龜兔賽跑問題用多線程實現

import java.util.Date;
public class Test extends Thread{ private int tortoise_walk = 0; // 烏龜已跑長度存放變數
private int rabbit_walk = 0; // 兔子已跑長度存放變數
private int finish = 1000; // 終點
private volatile boolean hasWinner = false;// 勝利者誕生 /**
*
* @ClassName: Tortoise_Run
* @Description: TODO(烏龜奔跑線程)
* @author guotingchao
* @date 2012-3-6 上午10:20:45
*
*/
class Tortoise_Run implements Runnable {
@Override
public void run() {
try {
while (!hasWinner) {
if (tortoise_walk % 100 == 0 && (tortoise_walk != 0||tortoise_walk>=finish)) { //烏龜每100米休息500毫秒
System.out.println("烏龜休息中………………");
Thread.sleep(500);
}
tortoise_walk++;
System.out.println("烏龜已跑"+tortoise_walk+"米");
}

} catch (InterruptedException e) {
e.printStackTrace();
}
}
} /**
*
* @ClassName: Rabbit_Run
* @Description: TODO(兔子奔跑線程)
* @date 2012-3-6 上午10:25:10
* @author guotingchao
*/
class Rabbit_Run implements Runnable {
@Override
public void run() {
try {
while (!hasWinner) {
if (rabbit_walk % 20 == 0 && (rabbit_walk != 0||rabbit_walk>=finish)) { //兔子每20米休息500毫秒
System.out.println("兔子休息中………………");
Thread.sleep(500);
}
rabbit_walk=rabbit_walk+5; //每秒跑5步
System.out.println("兔子已跑"+rabbit_walk+"米");
}

} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void run(){
new Thread(new Rabbit_Run()).start();
new Thread(new Tortoise_Run()).start();
}
/**
* @Title: main
* @Description: TODO(
* 賽程1000米,兔子跑5米,烏龜跑1米,兔子每20米休息500毫秒,烏龜每100米休息500毫秒。誰先到終點就結束程序
* ,並顯示獲勝方。)
* @param @param args
* @param @throws Exception 設定文件
* @author guotingchao
* @return void 返回類型
* @throws
*/
public static void main(String[] args) throws Exception {
long temp_actionTime=System.currentTimeMillis();
System.out.println("比賽開始:"+new Date(temp_actionTime)+"毫秒");
Test t=new Test();
new Thread(t).start();
while(true){
if(t.tortoise_walk>=t.finish||t.rabbit_walk>=t.finish){
t.hasWinner=true;
break;
}
}
String winnnerName=t.tortoise_walk>t.rabbit_walk?"烏龜":"兔子";
long temp_lastTime=System.currentTimeMillis();
System.out.println(winnnerName+"勝利");
System.out.println("比賽結束:"+new Date(temp_lastTime)+"毫秒");
System.out.println("所耗時間:"+(temp_lastTime-temp_actionTime)+"毫秒");
System.out.println("兔子="+t.rabbit_walk+" 烏龜="+t.tortoise_walk);
}
}
//不知道兔子和烏龜的步長時間是否按每秒。 這里程序只考慮依次遞增頻率

H. java多線程有幾種實現方法

I. java使用多線程模擬這一過程

packageknow;
publicclassT31{

publicstaticintpeaches=100;

(intnum,intmypeach){
inti=peaches/2+peaches%2;
peaches-=i;
mypeach+=i;
System.out.println("第"+num+"只猴子搶到了桃子,這次搶到"+i+"個,現在有:"+mypeach+"個");
returnmypeach;
}
publicstaticvoidmain(String[]args)throwsInterruptedException{
Threadmonkey1=newThread(){
publicvoidrun(){
intmypeach=0;
while(peaches>1){
mypeach=fetch(1,mypeach);
}

}
};
Threadmonkey2=newThread(){
publicvoidrun(){
intmypeach=0;
while(peaches>1){
mypeach=fetch(2,mypeach);
}

}
};
Threadmonkey3=newThread(){
publicvoidrun(){
intmypeach=0;
while(peaches>1){
mypeach=fetch(3,mypeach);
}

}
};
monkey1.start();
monkey2.start();
monkey3.start();
}
}

J. java多線程--模擬接力賽跑

import java.util.*;

public class Main {
public static void main(String[] args) {
RunThread run = new RunThread();
for (int i = 1; i <= 5; ++i) {
new Thread(run, i + "號選手").start();
}
}
}

class RunThread implements Runnable {
int distance;

@Override
public synchronized void run() {
String name = Thread.currentThread().getName();
System.out.println(name + "拿到接力棒!");
for (int i = 0; i < 10; ++i) {
distance += 10;
System.out.println(name + "跑到了" + distance + "米!");
}
}

}

閱讀全文

與java模擬多線程相關的資料

熱點內容
python超簡單編程 瀏覽:257
獲取命令方 瀏覽:976
怎樣製作文件夾和圖片 瀏覽:58
調研編譯寫信息 瀏覽:859
python馮諾依曼 瀏覽:417
同時安裝多個app有什麼影響 瀏覽:253
奧術殺戮命令宏 瀏覽:182
用sdes加密明文字母e 瀏覽:359
單片機原理及應用試題 瀏覽:423
易語言開啟指定文件夾 瀏覽:40
馬思純參加密室大逃脫 瀏覽:322
文件夾冬季澆築溫度 瀏覽:712
京東有返點的aPp叫什麼 瀏覽:603
如何查看u點家庭伺服器是幾兆 瀏覽:262
python應用介面怎麼接 瀏覽:67
腐蝕怎麼進不去伺服器啊 瀏覽:359
linuxcpiogz 瀏覽:631
安卓中的布局是什麼文件 瀏覽:397
dex反編譯部分代碼無法查看 瀏覽:464
linuxandroid編譯 瀏覽:603