parent
7b25fba156
commit
613a771890
@ -0,0 +1,127 @@
|
||||
1.使用synchronized关键字同步线程
|
||||
package step2;
|
||||
|
||||
public class Task {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
final insertData insert = new insertData();
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
new Thread(new Runnable() {
|
||||
public void run() {
|
||||
insert.insert(Thread.currentThread());
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
class insertData {
|
||||
|
||||
public static int num = 0;
|
||||
|
||||
/********* Begin *********/
|
||||
public synchronized void insert(Thread thread) {
|
||||
|
||||
for (int i = 0; i <= 5; i++) {
|
||||
num++;
|
||||
System.out.println(num);
|
||||
}
|
||||
}
|
||||
|
||||
/********* End *********/
|
||||
}
|
||||
2.创建线程
|
||||
package step1;
|
||||
|
||||
//请在此添加实现代码
|
||||
/********** Begin **********/
|
||||
public class ThreadClassOne extends Thread {
|
||||
public void run(){
|
||||
for(int i=1;i<10;i+=2){
|
||||
System.out.print(i+" ");
|
||||
}
|
||||
}
|
||||
}
|
||||
class ThreadClassTwo implements Runnable{
|
||||
public void run(){
|
||||
for(int i=0;i<=10;i+=2){
|
||||
System.out.print(i+" ");
|
||||
}
|
||||
}
|
||||
public void start(){
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/********** End **********/
|
||||
|
||||
3.顺序输出
|
||||
package step1;
|
||||
|
||||
public class Task {
|
||||
public static void main(String[] args) throws Exception {
|
||||
/********* Begin *********/
|
||||
// 在这里创建线程, 开启线程
|
||||
|
||||
Object a = new Object();
|
||||
Object b = new Object();
|
||||
Object c = new Object();
|
||||
// 在这里创建线程, 开启线程
|
||||
MyThread th1 = new MyThread("AA", a, c);
|
||||
MyThread th2 = new MyThread("BB", c, b);
|
||||
MyThread th3 = new MyThread("CC", b, a);
|
||||
|
||||
th1.start();
|
||||
Thread.sleep(10);
|
||||
th2.start();
|
||||
Thread.sleep(10);
|
||||
th3.start();
|
||||
Thread.sleep(10);
|
||||
System.exit(0);
|
||||
|
||||
/********* End *********/
|
||||
}
|
||||
}
|
||||
|
||||
class MyThread extends Thread {
|
||||
/********* Begin *********/
|
||||
|
||||
String threadName;
|
||||
Object a = null;
|
||||
Object b = null;
|
||||
|
||||
public MyThread(String threadName, Object a, Object b) {
|
||||
super();
|
||||
this.threadName = threadName;
|
||||
this.a = a;
|
||||
this.b = b;
|
||||
}
|
||||
|
||||
public synchronized void run() {
|
||||
|
||||
int count = 5;
|
||||
while (count > 0) {
|
||||
synchronized (a) {
|
||||
synchronized (b) {
|
||||
System.out.println("Java Thread" + this.threadName);
|
||||
count--;
|
||||
b.notify();
|
||||
|
||||
}
|
||||
try {
|
||||
a.wait();
|
||||
} catch (InterruptedException e) {
|
||||
// TODO 自动生成的 catch 块
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
/********* End *********/
|
||||
}
|
||||
|
Loading…
Reference in new issue