1.简单的多线程例子
package test;
public class hello {
public static void main(String args[]){
Runnable printA = new PrintChar('a',100);
Runnable printB = new PrintChar('b',100);
Runnable printC = new PrintChar('c',100);
Thread A = new Thread(printA);
Thread B = new Thread(printB);
Thread C = new Thread(printC);
A.start();
B.start();
C.start();
}
}
class PrintChar implements Runnable{
private char c;
private int i;
public PrintChar(char c, int i) {
this.c = c;
this.i = i;
}
@Override
public void run() {
for(int k=0;k<i;k++)
System.out.print(c);
}
}
其中若将A.start()等改成A.run();最后实现的结果是打印100个A然后打印100个B最后打印100C,没有实现多线程并行操作。
2.创建一个线程池
创建一个有三个固定线程的线程池
ExecutorService exe = Executors.newFixedThreadPool(3);
创建一个可变的线程池:
ExecutorService exe = Executors.newCachedThreadPool();
3.线程同步与同步语句
package test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Account {
private static account acc = new account();
public static void main(String args[]){
ExecutorService exe = Executors.newCachedThreadPool();
for(int i=0;i<10000;i++){
exe.execute(new addmoney());}
exe.shutdown();
while(!exe.isTerminated()){}
System.out.println(acc.getbal());
}
private static class addmoney implements Runnable{
public void run(){
synchronized(acc){
acc.dep(1);}}
}
private static class account{
private int balance = 0;
private int getbal(){
return balance;
}
public void dep(int m){
int newbalance =balance+ m;
try{
Thread.sleep(5);
}
catch(InterruptedException ex){}
balance = newbalance;
}
}
}
其中若将
synchronized(acc)
这里acc改成this将不能实现同步。
另外可以在
public void dep(int m)
这里加入关键字synchronized实现同步,另外在方法体中使用synchronized(this){method}也可以实现同步。使用lock也可以显示的实现锁,使用Lock lock=new ReentrantLock()创建锁。
4.线程之间协作
使用该语句可以创建线程之间的唤醒条件实现线程之间的协作