- package com.itheima.Demo;
- import java.util.Random;
- public class Test1 {
- public static void main(String[] args) {
- String[] str = {"爬山","游泳","羽毛球","乒乓球","网球"};
- todo something = new todo(str);
- new Thread(something,"ls").start();;
- new Thread(something,"zs").start();;
- }
- }
- class todo implements Runnable{
- private String[] str;
- //把num定义为私有成员变量,保证了多个线程值操作以个num 当有一个线程,num等与6的时候就会结束。
- private int num = 0;
- private Random r = new Random();
- public todo(String[] str){
- this.str = str;
- }
-
- @Override
- public void run() {
- while(num < 6){
- synchronized(this){
- if(num<6){
-
- int i = r.nextInt(str.length);
- String name = Thread.currentThread().getName();
- System.out.println(name + "要去" + str[i]);
- num++;
- try {
- this.wait(10);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- }
复制代码 |