0%

java线程

一个进程是一个独立的程序运行单位:包括了内存,编译好的二进制代码,寄存器,堆践等等。

线程是最小的逻辑执行单元,只有在运行的时候才会有自身的寄存器等等。

一个进程可以多个线程。

  • 由于线程共享公共变量,所以对于公共变量的更改要加锁以便防止并发改,或者一个线程执行到一半,又有另外的线程更改。造成数据不一致。

Java线程的创建或是执行方式:

1:使用lambda方式实现及实现Runnable接口

                      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Runnable r = ()-> {
try {
while (true) {
int toAccount = (int) (bank.size() * Math.random());
double amount = balance * Math.random();
System.out.print(formAccount);
System.out.print("-");
System.out.print(toAccount);
System.out.print("-");
System.out.print(amount);
System.out.print("\n");
bank.tranfer(formAccount, toAccount, amount);
Thread.sleep(10);
}
}catch (Exception $e) {

}

};

Thread t = new Thread(r);
t.start();

2:继承并实现thread的run方法

二:线程的状态

​ new(新建)

​ runnable(可运行)

​ blocked(阻塞)

​ waiting(等待)

​ timed waiting (计时等待)

​ terminated(被终止)

三:线程之间的锁机制

​ 3.1使用Lock和Condition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package Thread;
import java.util.*;
import java.util.concurrent.locks.*;

public class Bank {
private final double[] accounts;
private Lock bankLock;
private Condition sufficientFunds;
/**
* Constructs the bank.
* @param n the number of accounts
* @param initialBalance the initial balance for each account
*/
public Bank(int n, double initialBalance)
{
accounts = new double[n];
Arrays.fill(accounts, initialBalance);
bankLock = new ReentrantLock();
sufficientFunds = bankLock.newCondition();
}

/**
* Transfers money from one account to another.
* @param from the account to transfer from
* @param to the account to transfer to
* @param amount the amount to transfer
*/
public void tranfer(int from, int to, double amount) throws InterruptedException
{
bankLock.lock();
try {
while (accounts[from] < amount)
sufficientFunds.await();
accounts[from] -= amount;
System.out.print(Thread.currentThread()) ;
System.out.printf(" %10.2f from %d to %d", amount, from, to);
accounts[to] += amount;
System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
System.out.print("\n");
sufficientFunds.signalAll();

} finally {
bankLock.unlock();
}
}

public double getTotalBalance()
{
bankLock.lock();
try {
double sum = 0;
for (double item : accounts) {
sum += item;
}
return sum;
} finally {
bankLock.unlock();
}

}

public int size()
{
return accounts.length;
}
}

3.2使用synchronized

synchronized关键字类似于lock用来锁定代码执行区域。

​ public synchronized void methodName()

{

​ local;

​ …method

​ unlock;

}

   
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package Thread;
import java.util.*;
import java.util.concurrent.locks.*;

public class Bank {
private final double[] accounts;
//private Lock bankLock;
//private Condition sufficientFunds;
/**
* Constructs the bank.
* @param n the number of accounts
* @param initialBalance the initial balance for each account
*/
public Bank(int n, double initialBalance)
{
accounts = new double[n];
Arrays.fill(accounts, initialBalance);
//bankLock = new ReentrantLock();
//sufficientFunds = bankLock.newCondition();
}

/**
* Transfers money from one account to another.
* @param from the account to transfer from
* @param to the account to transfer to
* @param amount the amount to transfer
*/
public synchronized void tranfer(int from, int to, double amount) throws InterruptedException
{
while (accounts[from] < amount)
wait();
accounts[from] -= amount;
System.out.print(Thread.currentThread()) ;
System.out.printf(" %10.2f from %d to %d", amount, from, to);
accounts[to] += amount;
System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
System.out.print("\n");
notifyAll();
}
// public void tranfer(int from, int to, double amount) throws InterruptedException
// {
// bankLock.lock();
// try {
// while (accounts[from] < amount)
// sufficientFunds.await();
// accounts[from] -= amount;
// System.out.print(Thread.currentThread()) ;
// System.out.printf(" %10.2f from %d to %d", amount, from, to);
// accounts[to] += amount;
// System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
// System.out.print("\n");
// sufficientFunds.signalAll();
//
// } finally {
// bankLock.unlock();
// }
// }

public synchronized double getTotalBalance()
{
//bankLock.lock();
try {
double sum = 0;
for (double item : accounts) {
sum += item;
}
return sum;
} finally {
// bankLock.unlock();
}

}

public int size()
{
return accounts.length;
}
}

四:线程安全的集合

五:线程池