java多執行緒 例子

2021-08-01 04:07:15 字數 2527 閱讀 5250

題目:一共有100個饅頭,40個工人,每個工人最多可以吃3個饅頭,使用多執行緒輸出所有工人吃饅頭的情況。

程式很簡單,設計如下:

public

class

mantoudemo

}}class

worker

extends

thread

public

void run()

//如果沒吃飽,繼續取饅頭

int t=basket.getmantou();

//如果發現已經沒有饅頭了,則直接返回

if(t==0)

//如果還有,則可以繼續取饅頭,直到達到最大值3

n++;

system.out.println(name+":"+t);}}

}class

basket

}

程式結果:

worker-1:100

worker-2:99

worker-1:98

worker-1:96

worker-2:97

worker-2:94

worker-3:95

worker-3:93

worker-3:92

worker-4:91

worker-4:90

worker-4:89

worker-5:88

worker-5:87

worker-5:86

worker-6:85

worker-6:84

worker-6:83

worker-7:82

worker-7:81

worker-7:80

worker-8:79

worker-8:78

worker-8:77

worker-9:76

worker-9:75

worker-9:74

worker-10:73

worker-10:72

worker-11:71

worker-10:70

worker-11:69

worker-12:68

worker-11:67

worker-12:66

worker-12:64

worker-13:65

worker-13:63

worker-14:62

worker-13:61

worker-14:60

worker-14:58

worker-15:59

worker-15:57

worker-15:55

worker-16:56

worker-16:54

worker-16:53

worker-17:52

worker-17:51

worker-17:50

worker-18:49

worker-18:48

worker-18:47

worker-19:46

worker-19:45

worker-19:44

worker-20:43

worker-20:42

worker-20:41

worker-21:40

worker-21:39

worker-21:38

worker-22:37

worker-22:36

worker-22:35

worker-23:34

worker-23:33

worker-23:32

worker-24:31

worker-24:30

worker-24:29

worker-25:28

worker-25:27

worker-25:26

worker-26:25

worker-26:24

worker-26:23

worker-27:22

worker-27:21

worker-27:20

worker-28:19

worker-28:18

worker-28:17

worker-29:16

worker-29:15

worker-29:14

worker-30:13

worker-30:12

worker-30:11

worker-31:10

worker-31:9

worker-31:8

worker-32:7

worker-33:6

worker-33:5

worker-33:3

worker-32:4

worker-32:1

worker-37:2

多執行緒例子

coding utf 8 import threading import queue import time import random from faker import faker class mythread threading.thread 執行緒模型 def init self,queue...

POSIX執行緒多執行緒例子

include include include include define num threads 6 void thread function void arg int main sleep 1 printf waiting for threads to finish.n for lots of...

多執行緒實例子

class threaddemo1 catch exception e system.out.println main thread.currentthread getname testthread tt new testthread tt.start tt.start tt.start tt.st...